前提:
开通smtp服务,如果是126或163邮件步骤如下:
1、打开 “POP3/SMTP/IMAP” 菜单,如下图:
2、点击开启,如下图:
3、点继续开启,如下图:
4、通过手机发送短信
5、点击下图中的“我已发送”
6、开通成功,得到设备码(备注:此设备码就做为MailKit里的密码)。
代码:
首先使用nuget引用MailKit,然后测试代码如下:
string mailAccount = "abc@126.com"; string mainPassword = "ABVCDEFGDSDF"; var client = new MailKit.Net.Smtp.SmtpClient(); client.Connect("smtp.126.com", 25, SecureSocketOptions.None); client.AuthenticationMechanisms.Remove("XOAUTH2"); client.Authenticate(mailAccount, mainPassword); var message = new MimeMessage(); message.From.Add(new MailboxAddress("testNameFrom", "abc@126.com")); message.To.Add(new MailboxAddress("testNameTo", "abcd@163.com")); message.Subject = "测试发送邮件的标题"; var html = new TextPart("html") { Text = @"<p>您好,张三:<br> <p>附件里是详细内容,请查收!<br> <p>-- 管家王小明<br>" }; var alternative = new Multipart("alternative"); alternative.Add(html); string pngPath = @"C:UserswjxDesktoplogo.png"; var attachmentPng = new MimePart("image", "png") { Content = new MimeContent(File.OpenRead(pngPath), ContentEncoding.Default), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Base64, FileName = Path.GetFileName(pngPath) }; string zipPath = @"C:UserswjxDesktop中国百度的logo.zip"; var attachmentZip = new MimePart("application", "zip") { Content = new MimeContent(File.OpenRead(zipPath), ContentEncoding.Default), ContentDisposition = new ContentDisposition(ContentDisposition.Attachment), ContentTransferEncoding = ContentEncoding.Base64, FileName = Path.GetFileName(zipPath) }; var multipart = new Multipart("mixed"); multipart.Add(alternative); multipart.Add(attachmentPng); multipart.Add(attachmentZip); message.Body = multipart; client.Send(message); client.Disconnect(true);