一 、在.Net Core中MailKit中提供了邮件的基础封装
它支持跨平台,并且支持 IMAP, POP3, SMTP 等协议
Nuget命令:
Install-Package MailKit
官方Git地址:https://github.com/jstedfast/MailKit
二、使用实例:
MimeMessage message = new MimeMessage();
//发件人
message.From.Add(new MailboxAddress("张三丰", "xxx@qq.com"));
//收件人
message.To.Add(new MailboxAddress("测试", "xxx@163.com"));
//标题
message.Subject = "测试标题内容";
//产生一个支持HTml 的TextPart
TextPart body = new TextPart(TextFormat.Html)
{
Text = "<h1>测试内容</h1>"
};
//创建Multipart添加附件
Multipart multipart = new Multipart("mixed");
multipart.Add(body);
//附件
string absolutePath = @"F:\桌面\新建文件夹\mysql1.sql";
MimePart attachment = new MimePart()
{
//读取文件,只能用绝对路径
ContentObject = new ContentObject(File.OpenRead(absolutePath), ContentEncoding.Default),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
//文件名字
FileName = Path.GetFileName(absolutePath)
};
multipart.Add(attachment);
//正文内容,发送
message.Body = multipart;
//message.Body = body;
using (SmtpClient client = new SmtpClient())
{
//Smtp服务器
client.Connect("smtp.qq.com", 587, false);
//登录,发送
//特别说明,对于服务器端的中文相应,Exception中有编码问题,显示乱码了
client.Authenticate("xxx@qq.com", "xxx");
client.Send(message);
//断开
client.Disconnect(true);
Console.WriteLine("发送邮件成功");
}
三、关于邮件中待手机号的识别测试如下:
MimeMessage message = new MimeMessage();
//发件人
message.From.Add(new MailboxAddress("xxx@qq.com"));
//收件人
message.To.Add(new MailboxAddress("xxxx@qq.com"));
//标题
message.Subject = "测试";
//内容
TextPart body = new TextPart(TextFormat.Html)
{
//a标签正常的话会被 客户端屏蔽掉
//Text = "<h1>测试内容</h1> <a href='tel:15154123615'>15154123615</a>"
//a标签不正常关闭,客户端可以一键拨打(支持在IOS的QQ端,QQ邮箱App端 原因:这两个客户端对于手机号自动识别)
//在微信提醒客户端中就不支持
Text = "<h1>测试内容</h1> <a href='tel:15154123615'>15154123615</tel>"
};
message.Body = body;
using (SmtpClient client = new SmtpClient())
{
//smtp服务器
client.Connect("smtp.qq.com", 587, false);
//登录账号
client.Authenticate("xxxx@qq.com", "password");
client.Send(message);
client.Disconnect(true);
Console.WriteLine("邮件发送成功");
}
四、实例
using System;
using MailKit.Net.Smtp;
using MimeKit;
namespace mail
{
class Program
{
static void Main(string[] args)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Luskyle", "*******@qq.com"));//这里是你的qq邮箱,如果要改后缀的话下边端口和smtp主机地址也要改
message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "******@163.com"));//这里是接收人的邮箱
message.Subject = "How you doin'?";//邮箱头
message.Body = new TextPart("plain")
{
Text = @"Hey Chandler,
I just wanted to let you know that Monica and I were going to go play some paintball, you in?
-- Joey"//这里是内容(各位随意发挥)
};
using (var client = new SmtpClient())
{
client.Connect("smtp.qq.com", 587, false);
//腾讯qq邮箱的smtp主机地址为:smtp.qq.com 端口是587。
// Note: only needed if the SMTP server requires authentication
client.Authenticate("********@qq.com", "授权码");//发件人的邮箱账号,发件人的授权码
client.Send(message);
client.Disconnect(true);
Console.Write("OK");
}
}
}
}