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