我有一個接口,用於發送郵件如何EmailMessage交替意見轉換成SendGrid HTML和文本
public interface IMailSender
{
void SendMail(MailMessage message);
}
當我創建郵件我用AlternateView爲(純文本和HTML)
現在我想創建一個實現該接口的SendGridMailSender類,但我的問題是,我不知道如何填充基於MailMessage的SendGrid.Html和SendGrid.Text。我能找到的唯一解決方案意味着使用StreamReader並通過索引訪問AlternateViewsCollection,我希望有一個更好的解決方案,我無法弄清楚。
public void SendMail(MailMessage message)
{
var sendGridMessage = CreateSendGridMessage(message);
// Create network credentials to access your SendGrid account.
var user = "userCredential";
var pswd = "userPaswd";
var credentials = new NetworkCredential(user, pswd);
// Create an SMTP transport for sending email.
var transportSMTP = SMTP.GetInstance(credentials);
// Send the email.
transportSMTP.Deliver(sendGridMessage);
}
private SendGrid CreateSendGridMessage(MailMessage mail)
{
var sendGridMessage = SendGrid.GetInstance();
sendGridMessage.From = mail.From;
var recipients = mail.To;
foreach (var recipient in recipients)
{
sendGridMessage.AddTo(recipient.ToString());
}
var stream = mail.AlternateViews[0].ContentStream;
using (var reader = new StreamReader(stream))
{
sendGridMessage.Text = reader.ReadToEnd();
}
stream = mail.AlternateViews[1].ContentStream;
using (var reader = new StreamReader(stream))
{
sendGridMessage.Html = reader.ReadToEnd();
}
return sendGridMessage;
}
感謝
我注意到你之前問過這個問題是因爲我在刪除它之前留下了一個以前版本的評論,所以最好更新原始問題而不是重新發布FYI。 – Swift
是的,斯威夫特。爲了澄清這個問題,我正要更新它,但說實話,它太雜亂了,甚至在幾個小時後我都很難理解它。無論如何,你可能是對的,即使我應該編輯它,我的錯 – mitomed