如何使用sendgridmail发送包含多个附件的邮件?

时间:2015-01-22 11:37:27

标签: asp.net c#-4.0 sendgrid

我正在进行的项目要求向具有多个文件附件的用户发送电子邮件。我正在使用发送网格邮件dll来发送邮件。我搜索了很多,但没有找到任何可靠的解决方案。 任何人都可以帮忙吗? 这是我的代码:

 public void SimpleHTMLEmailWithAttachment(String emailBody, String subject, MailId mailId, System.IO.MemoryStream ms, String fileName)
    {
        //create a new message object
        var message = SendGrid.GetInstance();

        //set the message recipients
        message.AddTo(this.to);

        //set the sender
        message.From = new MailAddress(from);

        //set the message body
        message.Html = emailBody;

        //set the message subject
        message.Subject = subject;

        //set the attachment

        message.AddAttachment(ms, fileName);
        //set unique identifier
        Dictionary<String, String> identifier = new Dictionary<String, String>();
        identifier.Add("MailId", mailId.AsString());
        message.Header.AddUniqueIdentifier(identifier);

        //create an instance of the Web transport mechanism
        var transportInstance = Web.GetInstance(new NetworkCredential(userName, password));

        //send the mail
        transportInstance.Deliver(message);
    }

1 个答案:

答案 0 :(得分:3)

根据api文档,您可以简单地为每个附件多次调用该方法。

message.AddAttachment(ms, fileName);
message.AddAttachment(ms2, fileName2);

您可能还需要传入其他内存流和文件名。

传入包含内存流和文件名的字典可能更好。

见下文。

public void SimpleHTMLEmailWithAttachment(String emailBody, String subject, MailId mailId, Dictionary<string, MemoryStream> Files)
    {
        //create a new message object
        var message = SendGrid.GetInstance();

        //set the message recipients
        message.AddTo(this.to);

        //set the sender
        message.From = new MailAddress(from);

        //set the message body
        message.Html = emailBody;

        //set the message subject
        message.Subject = subject;

        //set the attachment

    foreach(var key in Files.Keys)
    {
       var ms = Files[key];
       message.AddAttachment(ms, key);
    }

        //set unique identifier
        Dictionary<String, String> identifier = new Dictionary<String, String>();
        identifier.Add("MailId", mailId.AsString());
        message.Header.AddUniqueIdentifier(identifier);

        //create an instance of the Web transport mechanism
        var transportInstance = Web.GetInstance(new NetworkCredential(userName, password));

        //send the mail
        transportInstance.Deliver(message);
    }