69 lines
2.1 KiB
C#
69 lines
2.1 KiB
C#
|
using System.Net;
|
|||
|
using System.Net.Mail;
|
|||
|
using System.Net.Mime;
|
|||
|
using System.Text;
|
|||
|
using Bunny.Dao.Entity.Email;
|
|||
|
|
|||
|
namespace Bunny.Common.Utils;
|
|||
|
|
|||
|
public class EmailUtil
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
/// 发送邮件,建议使用QQ端口587,465发送不成功
|
|||
|
/// </summary>
|
|||
|
public static void SendEmail(EmailSendEntity entity)
|
|||
|
{
|
|||
|
// 创建邮件发送对象
|
|||
|
var smtpClient = new SmtpClient();
|
|||
|
|
|||
|
// 设置发送者邮件和接受者邮件
|
|||
|
var sendMailAddress = new MailAddress(entity.SendEmail);
|
|||
|
var receiverMailAddress = new MailAddress(entity.ReceiverEmail);
|
|||
|
|
|||
|
// 创建邮件发送消息
|
|||
|
var mailMessage = new MailMessage(sendMailAddress, receiverMailAddress)
|
|||
|
{
|
|||
|
Subject = entity.Subject,
|
|||
|
SubjectEncoding = Encoding.UTF8,
|
|||
|
Body = entity.Body,
|
|||
|
BodyEncoding = Encoding.UTF8,
|
|||
|
IsBodyHtml = entity.IsHtml
|
|||
|
};
|
|||
|
|
|||
|
// 判断是否有抄送
|
|||
|
if (entity.CC != null)
|
|||
|
{
|
|||
|
var ccArray = entity.CC.Split(',');
|
|||
|
// 是抄送
|
|||
|
if (entity.IsBbc == false)
|
|||
|
foreach (var ccAddress in ccArray)
|
|||
|
mailMessage.CC.Add(new MailAddress(ccAddress));
|
|||
|
|
|||
|
// 是密送
|
|||
|
else
|
|||
|
foreach (var ccAddress in ccArray)
|
|||
|
mailMessage.Bcc.Add(new MailAddress(ccAddress));
|
|||
|
}
|
|||
|
|
|||
|
|
|||
|
// 如果设置了富文本
|
|||
|
if (entity.IsHtml)
|
|||
|
{
|
|||
|
// 设置HTML文本
|
|||
|
var htmlView = AlternateView
|
|||
|
.CreateAlternateViewFromString(entity.Body, Encoding.UTF8, MediaTypeNames.Text.Html);
|
|||
|
|
|||
|
// 添加富文本视图到邮件消息
|
|||
|
mailMessage.AlternateViews.Add(htmlView);
|
|||
|
}
|
|||
|
|
|||
|
// 创建SMTP客户端并发送邮件
|
|||
|
smtpClient.Credentials = new NetworkCredential(entity.SendEmail, entity.SendEmailPassword);
|
|||
|
smtpClient.EnableSsl = true;
|
|||
|
smtpClient.Port = entity.SmtpPort;
|
|||
|
smtpClient.Host = entity.SmtpService;
|
|||
|
|
|||
|
// 发送邮件
|
|||
|
smtpClient.Send(mailMessage);
|
|||
|
}
|
|||
|
}
|