2013-05-20 35 views
3

我有一個接口,用於發送郵件如何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; 
} 

感謝

+0

我注意到你之前問過這個問題是因爲我在刪除它之前留下了一個以前版本的評論,所以最好更新原始問題而不是重新發布FYI。 – Swift

+0

是的,斯威夫特。爲了澄清這個問題,我正要更新它,但說實話,它太雜亂了,甚至在幾個小時後我都很難理解它。無論如何,你可能是對的,即使我應該編輯它,我的錯 – mitomed

回答

3

只有這樣,才能訪問AlternateView內容是通過流什麼,所以你的解決方案是正確的,但你也應該檢查ContentType以確保mail.AlternateViews[0]實際上是您的文本部分等等。

0

你有沒有想過使用官方的C#庫,而不是?這使得它超級簡單的做你想做

// Create the email object first, then add the properties. 
var myMessage = SendGrid.GetInstance(); 

// Add the message properties. 
myMessage.From = new MailAddress("[email protected]"); 

// Add multiple addresses to the To field. 
List<String> recipients = new List<String> 
{ 
    @"Jeff Smith <[email protected]>", 
    @"Anna Lidman <[email protected]>", 
    @"Peter Saddow <[email protected]>" 
}; 

myMessage.AddTo(recipients); 

myMessage.Subject = "Testing the SendGrid Library"; 

//Add the HTML and Text bodies 
myMessage.Html = "<p>Hello World!</p>"; 
myMessage.Text = "Hello World plain text!"; 

https://github.com/sendgrid/sendgrid-csharp

+0

謝謝斯威夫特。是的,這是我的原始代碼,但我現在想要實現的是實現接口,爲此我需要接收MailMessage作爲參數。 SendGrid實例/消息的其餘部分似乎很容易填充,但這些Html和Text正文不包含,因爲我只能使用該流讀取器 – mitomed