Как я могу отправить почту с более чем одним вложением с помощью sendgridmail?

Мой текущий проект требует отправки электронной почты пользователю с более чем одним вложенным файлом. Я использую dll send grid mail для отправки почты. я много искал, но не нашел надежного решения. Кто-нибудь может помочь? Вот мой код:

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

person Asif Rehman    schedule 22.01.2015    source источник


Ответы (1)


Согласно документации 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);
    }
person scartag    schedule 22.01.2015
comment
Письмо успешно отправлено с двумя вложениями. Спасибо - person Asif Rehman; 22.01.2015