C#对邮件的支持
SMTP协议
SMTP的全称是“Simple Mail Transfer Protocol”,即简单邮件传输协议。它是一组用于从>源地址到目的地址传输邮件的规范,通过它来控制邮件的中转方式。SMTP 协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。SMTP 服务器就是遵循SMTP协议的发送邮件服务器。SMTP认证,简单地说就是要求必须在提供了账户名和密码之后才可以登录 SMTP 服务器,这就使得那些垃圾邮件的散播者无可乘之机。增加 SMTP 认证的目的是为了使用户避免受到垃圾邮件的侵扰。
而.NET平台下对Mail的发送封装的已经很完善了,引用库
System.Net.Mail;
System.Net.Mime;
MailPlatform.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
namespace MailApi
{
public class MailPlatform
{
private List<(MailAddress,string)>? _mailinformation;
public MailPlatform(IList<(MailAddress,string)>? pairs)
{
_mailinformation = (List<(MailAddress, string)>?)pairs ?? throw new Exception("错误的初始化");
}
public void SendMail(MailMessage message)
{
var info = _mailinformation?.OrderBy(s => Guid.NewGuid()).FirstOrDefault() ?? throw new Exception("未初始化任何设置");
message.From = info.Item1;
var client = new SmtpClient()
{
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(info.Item1.Address, info.Item2),
DeliveryMethod = SmtpDeliveryMethod.Network,
Host = "smtp." + info.Item1.Host
};
client.Send(message);
}
public void SendMailAsync(MailMessage message, SendCompletedEventHandler CompletedMethod, object args)
{
var info = _mailinformation?.OrderBy(s => Guid.NewGuid()).FirstOrDefault() ?? throw new Exception("未初始化任何设置");
message.From = info.Item1;
var client = new SmtpClient()
{
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(info.Item1.Address, info.Item2),
DeliveryMethod = SmtpDeliveryMethod.Network,
Host = "smtp." + info.Item1.Host
};
client.SendCompleted += new SendCompletedEventHandler(CompletedMethod);
client.SendAsync(message, args);
}
}
}
MailPlatform类用于发送邮件,在实例化MailPlatform的时候,IList<(MailAddress,string)>? pairs
参数用于初始化发送方的邮件设置,而该平台的作用是随机调用平台里面的发送单元进行发送,避免多数据同时发送而造成堵塞等问题,初始化例子
MailPlatform platform = new MailPlatform(
new List<(MailAddress, string)>()
{
(new MailAddress("您的第一个邮箱"),"授权码"),
(new MailAddress("您的第二个邮箱"), "授权码"),
(new MailAddress("您的第n个邮箱"),"授权码")
});
发送的时候调用SendMail即可,传入的MailMessage可以用Builder进行初始化,而异步函数SendMailAsync,可以传入完成发送后的回调函数进行验证,args则为传入数据
MailBuilder.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net.Mime;
namespace MailApi
{
public class MailBuilder
{
public MailBuilder() { }
public List<string>? Address { set; get; } = new List<string>();
public string? Body { set; get; } = string.Empty;
public Encoding? Encoding { set; get; } = Encoding.UTF8;
public bool? IsHtml { set; get; } = true;
public string? Subject { set; get; } = string.Empty;
public List<string>? Attachments { set; get; } = new List<string>();
public MailMessage Build()
{
var message = new MailMessage();
if (Address?.Count == 0) throw new Exception("发送人不能为空");
foreach (var c in Address)
{
message.To.Add(c);
}
message.Subject = Subject;
message.Body = Body;
message.IsBodyHtml = IsHtml ?? true;
message.BodyEncoding = Encoding;
message.Priority = MailPriority.Normal;
message.SubjectEncoding = Encoding;
foreach(var c in Attachments)
{
if (!File.Exists(c)) throw new Exception("附件文件不存在");
var data = new Attachment(c, MediaTypeNames.Application.Octet);//实例化附件
data.ContentDisposition.CreationDate = File.GetCreationTime(c);
data.ContentDisposition.ModificationDate = File.GetLastAccessTime(c);
data.ContentDisposition.ReadDate = DateTime.Now;
message.Attachments.Add(data);//添加到附件中
}
return message;
}
public Task<MailMessage> BuildAsync()
{
Task<MailMessage> message = new Task<MailMessage>(() =>
{
var message = new MailMessage();
if (Address?.Count == 0) throw new Exception("发送人不能为空");
foreach (var c in Address)
{
message.To.Add(c);
}
message.Subject = Subject;
message.Body = Body;
message.IsBodyHtml = IsHtml ?? true;
message.BodyEncoding = Encoding;
message.Priority = MailPriority.Normal;
message.SubjectEncoding = Encoding;
foreach (var c in Attachments)
{
if (!File.Exists(c)) throw new Exception("附件文件不存在");
var data = new Attachment(c, MediaTypeNames.Application.Octet);//实例化附件
data.ContentDisposition.CreationDate = File.GetCreationTime(c);
data.ContentDisposition.ModificationDate = File.GetLastAccessTime(c);
data.ContentDisposition.ReadDate = DateTime.Now;
message.Attachments.Add(data);//添加到附件中
}
return message;
});
message.Start();
return message;
}
}
}
MailBuilder类可以快速创建MailMessage信息,例
builder.Body = @"纸墨青鸳而随风而舞";
builder.Subject = "这是一封测试信息";
builder.Address.Add("你的目标邮箱1");
builder.Address.Add("你的目标邮箱2");
builder.Attachments.Add("附件地址1");
builder.Attachments.Add("附件地址2");
var mail = builder.Build();
platform.SendMail(mail);
在该模式下,只需要向builder中增加一个Address和设置Body和Subject信息即可进行发送,快速而简洁
配置QQ邮箱的权限
Step1.登录邮箱后选择设置
Step2.选择账户
Step3.下滑
找到POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
Step4.开启POP3/SMTP服务
并验证拿到授权码