欢迎来到我的的博客园,祝大家学有所成,早点实现自己的人生理想。

Netcore使用MailKit进行邮件发送

public void TestSendMailDemo()
{
var message = new MimeKit.MimeMessage();
message.From.Add(new MimeKit.MailboxAddress("hotmail", "china-psu@hotmail.com"));
message.To.Add(new MimeKit.MailboxAddress("qq", "283775652@qq.com"));
message.Subject = "This is a Test Mail";
var plain = new MimeKit.TextPart("plain")
{
Text = @"不好意思,我在测试程序,Sorry!"
};
var html = new MimeKit.TextPart("html")
{
Text = @"<p>Hey geffzhang<br>
<p>不好意思,我在测试程序,Sorry!<br>
<p>-- Geffzhang<br>"
};
// create an image attachment for the file located at path
var path = "D:\\雄安.jpg";
var fs = File.OpenRead(path);
var attachment = new MimeKit.MimePart("image", "jpeg")
{

ContentObject = new MimeKit.ContentObject(fs, MimeKit.ContentEncoding.Default),
ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
ContentTransferEncoding = MimeKit.ContentEncoding.Base64,
FileName = Path.GetFileName(path)
};
var alternative = new MimeKit.Multipart("alternative");
alternative.Add(plain);
alternative.Add(html);
// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new MimeKit.Multipart("mixed");
multipart.Add(alternative);
multipart.Add(attachment);
message.Body = multipart;
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect("smtp.live.com", 587, false);

// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");

// Note: only needed if the SMTP server requires authentication
var mailFromAccount = "china-psu@hotmail.com";
var mailPassword = "xxxxxxxxxxxxxxxxxxx";
client.Authenticate(mailFromAccount, mailPassword);

client.Send(message);
client.Disconnect(true);
}
fs.Dispose();
}

posted @ 2017-04-17 14:19  宋兴柱  阅读(426)  评论(0编辑  收藏  举报