.net Core Mailkit send attachement from array

hncl picture hncl · Jan 1, 2017 · Viewed 7.1k times · Source

I am testing .Net Core MVC, which does not support System.Net.Mail, the only alternative I found is Mailkit, works well but can't figure out how to send attachments that I have stored in my database as binary. I used the following in MVC 5:

     var mail = new MailMessage();
     mail.Attachments.Add(new Attachment(new MemoryStream(attachment), 
     attachmentName, attachmentType));

How can I do it in MailKit.

Answer

Dronacharya picture Dronacharya · Jan 1, 2017

You need to create a builder and then add the attachments to it, the attachments can be either IFromFile or in Binary string. Hope this helps.

public async void SendEmail(string mailTo, string mailFrom, string cc, string subject, string message)
{
    var emailMessage = new MimeMessage();
    if (cc != null)
    {
        emailMessage.Cc.Add(new MailboxAddress(cc)); 
    }

    emailMessage.From.Add(new MailboxAddress("SenderName", "UserName"));
    emailMessage.To.Add(new MailboxAddress("mailTo"));
    emailMessage.Subject = subject;
    var builder = new BodyBuilder { TextBody = message };

    //Fetch the attachments from db
    //considering one or more attachments
    if (attachments != null)
    {
        foreach (var attachment in attachments.ToList())
        {
            builder.Attachments.Add(attachmentName, attachment, ContentType.Parse(attachmentType));
        }
    }
    emailMessage.Body = builder.ToMessageBody();
    using (var client = new SmtpClient())
    {
        var credentials = new NetworkCredential
        {
            UserName = "USERNAME",
            Password = "PASSWORD"
        };
        await client.AuthenticateAsync(credentials);
        await client.ConnectAsync("smtp.gmail.com", 587).ConfigureAwait(false);
        await client.SendAsync(emailMessage).ConfigureAwait(false);
        await client.DisconnectAsync(true).ConfigureAwait(false);              
    }   }