.net Core Mailkit从阵列发送附件 [英] .net Core Mailkit send attachement from array

查看:558
本文介绍了.net Core Mailkit从阵列发送附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试.Net Core MVC,它不支持System.Net.Mail,我发现的唯一选择是Mailkit,它工作正常,但无法弄清楚如何以二进制形式发送已存储在数据库中的附件.我在MVC 5中使用了以下内容:

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

如何在MailKit中做到这一点.

How can I do it in MailKit.

推荐答案

您需要创建一个构建器,然后向其添加附件,附件可以是IFromFile或二进制字符串. 希望这会有所帮助.

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

这篇关于.net Core Mailkit从阵列发送附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆