4

I have an interface for sending mails

public interface IMailSender
{
    void SendMail(MailMessage message);
}

When I create a mail I use AlternateView for that (plain text and html)

And now I would like to create a SendGridMailSender class that implements that interface, but my problem is that I don't know how to I populate the SendGrid.Html and SendGrid.Text based on the MailMessage. The only solution I could find means using a StreamReader and accesing the AlternateViewsCollection by index, I would like to thing there's a better solution that I can't figure out.

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;
}

Thanks

4

2 回答 2

4

访问 AlternateView 内容的唯一方法是通过流,因此您的解决方案是正确的,尽管您还应该检查ContentType以确保它mail.AlternateViews[0]实际上是您的 Text 部分等等。

于 2013-05-21T16:22:08.783 回答
0

您是否考虑过改用官方的 C# 库?它使做你想做的事情变得超级简单

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

// Add the message properties.
myMessage.From = new MailAddress("john@example.com");

// Add multiple addresses to the To field.
List<String> recipients = new List<String>
{
    @"Jeff Smith <jeff@example.com>",
    @"Anna Lidman <anna@example.com>",
    @"Peter Saddow <peter@example.com>"
};

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

于 2013-05-20T21:33:51.863 回答