Asif Rehman
Asif Rehman

Reputation: 13

How can i send mail with more than one attachment using sendgridmail?

My ongoing project require that to send email to user with more than one file attachment. I am using send grid mail dll to send mail. i searched a lot but did not find any reliable solution. Any one can help? Here is my code:

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

Upvotes: 0

Views: 1615

Answers (1)

scartag
scartag

Reputation: 17680

According to the api docs you can simply call the method multiple times for each attachment.

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

You'll probably need to pass in the other memorystream and filename as well.

Probably better to pass in a dictionary that holds a memorystream and a filename.

See below.

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

Upvotes: 4

Related Questions