一、c# 邮件发送,具体方法实现
二话不说,直接上代码:
<!--邮件发送配置-->
<add key="SmtpServer" value="smtp.exmail.qq.com" />
<add key="Address" value="xxx@powerchina.cn" />
<add key="Sender" value="xxx@powerchina.cn" />
<add key="Password" value="yyy" />
<add key="Port" value="465" />
<add key="SenderName" value="xxx公司" />
<add key="Domain" value="" />
<add key="SSL" value="true" />
using MimeKit;
using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
namespace SER
{
public class EmailHelper
{
static Logger _logger = LogManager.GetCurrentClassLogger();
public string SmtpServer { get { return ConfigurationManager.AppSettings["SmtpServer"]; } set { } }
public string Sender { get { return ConfigurationManager.AppSettings["Sender"]; } set { } }
public string SenderName { get { return ConfigurationManager.AppSettings["SenderName"]; } set { } }
public string Address { get { return ConfigurationManager.AppSettings["Address"]; } set { } }
public string Password { get { return ConfigurationManager.AppSettings["Password"]; } set { } }
public int Port { get { return ConfigurationManager.AppSettings["Port"].ToInt(); } set { } }
public string SSL { get { return ConfigurationManager.AppSettings["SSL"].ToString(); } set { } }
public string Domain { get; set; }
public EmailHelper()
{
this.SmtpServer = ConfigurationManager.AppSettings["SmtpServer"];
this.Sender = ConfigurationManager.AppSettings["Sender"];
this.SenderName = ConfigurationManager.AppSettings["SenderName"];
this.Password = ConfigurationManager.AppSettings["Password"];
this.Address = ConfigurationManager.AppSettings["Address"];
this.Port = ConfigurationManager.AppSettings["Port"].ToInt();
this.Domain = "";
this.SSL = ConfigurationManager.AppSettings["SSL"].ToString();
}
/// <summary>
/// 发送邮件器
/// </summary>
/// <param name="smtpServer">邮箱的smtp服务器</param>
/// <param name="sendMail">发送人邮箱</param>
/// <param name="senderName">发送人显示名称</param>
/// <param name="password">发送人登录密码</param>
/// <param name="port">发送端口</param>
public EmailHelper(string smtpServer, string sender, string senderName, string password, int port, string domain, string ssl)
{
this.SmtpServer = smtpServer;
this.Sender = sender;
this.SenderName = senderName;
this.Password = password;
this.Port = port;
this.Domain = domain;
this.SSL = ssl;
}
/// <summary>
/// 发送邮件器
/// </summary>
/// <param name="smtpServer">邮箱的smtp服务器</param>
/// <param name="sendMail">发送人邮箱</param>
/// <param name="senderName">发送人显示名称</param>
/// <param name="password">发送人登录密码</param>
/// <param name="port">发送端口</param>
public EmailHelper(string smtpServer, string address, string sender, string senderName, string password, int port, string domain, string ssl) : this(smtpServer, sender, senderName, password, port, domain, ssl)
{
this.Address = address;
}
/// <summary>
/// 发送邮件
/// </summary>
/// <param name="subject">标题</param>
/// <param name="body">内容</param>
/// <param name="tos">发送人列表</param>
public JsonResponse SendMail(MessageEmail mail, List<MessageEmailAttachment> attachments)
{
_logger.Info("发送邮件开始...");
JsonResponse vJsonResponse = new JsonResponse();
try
{
if (!string.IsNullOrEmpty(Domain))
{
#region 原生代码
string login = Sender;
if (Sender.IndexOf("@") > 0)
{
login = Sender.Substring(0, Sender.IndexOf("@"));
}
SmtpClient client = new SmtpClient(SmtpServer, Port);
client.Credentials = new NetworkCredential(login, Password, Domain);
if (SSL.ToLower() == "true")
{
client.EnableSsl = true;
}
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(Sender, SenderName, Encoding.UTF8);
string[] toArrary = mail.To.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string t in toArrary)
{
mailMessage.To.Add(t);
}
if (!string.IsNullOrWhiteSpace(mail.Cc))
{
string[] ccArrary = mail.Cc.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string cc in ccArrary)
{
mailMessage.CC.Add(cc);
}
}
//if (!string.IsNullOrWhiteSpace(mail.Bcc))
//{
// string[] bccArrary = mail.Bcc.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
// foreach (string bcc in bccArrary)
// {
// mailMessage.Bcc.Add(bcc);
// }
//}
mailMessage.Subject = mail.Subject;
mailMessage.SubjectEncoding = Encoding.UTF8;
mailMessage.Body = mail.Body;
mailMessage.BodyEncoding = Encoding.UTF8;
mailMessage.IsBodyHtml = mail.IsBodyHtmlFormat;
mailMessage.Priority = MailPriority.Normal;
if (attachments != null)
{
foreach (var file in attachments)
{
string ext = Path.GetExtension(file.FileName);
string contentType = "application/octet-stream";
Attachment data = new Attachment(new MemoryStream(file.FileData), file.FileName, contentType);
data.ContentDisposition.DispositionType = DispositionTypeNames.Attachment;
mailMessage.Attachments.Add(data);
}
}
client.Send(mailMessage);
client.Dispose();
vJsonResponse.Success = true;
#endregion
}
else
{
#region MailKit
MimeMessage mimeMsg = new MimeMessage();
mimeMsg.From.Add(new MailboxAddress(Encoding.UTF8, SenderName, Address));
string[] toArrary2 = mail.To.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string t in toArrary2)
{
mimeMsg.To.Add(new MailboxAddress(t, t));
}
if (!string.IsNullOrWhiteSpace(mail.Cc))
{
string[] ccArrary = mail.Cc.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string cc in ccArrary)
{
mimeMsg.To.Add(new MailboxAddress(cc, cc));
}
}
//if (!string.IsNullOrWhiteSpace(mail.Bcc))
//{
// string[] bccArrary = mail.Bcc.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
// foreach (string bcc in bccArrary)
// {
// mimeMsg.To.Add(new MailboxAddress(bcc, bcc));
// }
//}
Multipart multipart = new Multipart();
string subType = mail.IsBodyHtmlFormat ? "html" : "plain";
TextPart bodyPart = new TextPart(subType) { Text = mail.Body };
multipart.Add(bodyPart);
if (attachments != null)
{
foreach (var file in attachments)
{
string ext = Path.GetExtension(file.FileName);
string contentType = "application/octet-stream";
//Log.Log.Instance.Info(contentType);
MimePart data = new MimePart(contentType)
{
FileName = file.FileName,
ContentDisposition = new MimeKit.ContentDisposition(MimeKit.ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
ContentObject = new ContentObject(new MemoryStream(file.FileData))
};
data.ContentDisposition.Parameters.Add("GB18030", "FileName", file.FileName);
foreach (var param in data.ContentDisposition.Parameters)
param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
foreach (var param in data.ContentType.Parameters)
param.EncodingMethod = ParameterEncodingMethod.Rfc2047;
multipart.Add(data);
}
}
mimeMsg.Body = multipart;
mimeMsg.Subject = mail.Subject;
ServicePointManager.ServerCertificateValidationCallback = delegate (Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; };
using (MailKit.Net.Smtp.SmtpClient client2 = new MailKit.Net.Smtp.SmtpClient())
{
if (SSL.ToLower() == "true")
{
client2.Connect(SmtpServer, Port, MailKit.Security.SecureSocketOptions.SslOnConnect);
}
else
{
client2.Connect(SmtpServer, Port, false);
}
client2.Authenticate(Sender, Password);
client2.Send(mimeMsg);
client2.Disconnect(true);
vJsonResponse.Success = true;
_logger.Info("发送邮件结束...");
}
#endregion
}
}
catch (Exception ex)
{
vJsonResponse.Success = false;
vJsonResponse.Message = ex.Message;
_logger.Info("发送邮件异常:" + ex.Message);
}
return vJsonResponse;
}
}
public class MessageEmail
{
public Guid MessageEmailID { get; set; }
/// <summary>
/// 邮件标题
/// </summary>
public string Subject { get; set; }
/// <summary>
/// 发送内容
/// </summary>
public string Body { get; set; }
/// <summary>
/// 接受邮件地址(xxxxx@qq.com;xxxxx@qq.com)可用;分割开
/// </summary>
public string To { get; set; }
/// <summary>
/// 邮件内容是否为HTML格式。默认为HTML,还有TEXT。
/// </summary>
public bool IsBodyHtmlFormat { get; set; }
public string Cc { get; set; }
/// <summary>
/// 发送时间,如果为空,则立即发送
/// </summary>
public DateTime? WhenToSend { get; set; }
/// <summary>
/// 发送成功时间
/// </summary>
public DateTime? SendDate { get; set; }
public DateTime? CreateDate { get; set; }
/// <summary>
/// 发送状态:0,待发送;1,正在发送;2,已发送;3,发送失败
/// </summary>
public int Status { get; set; }
/// <summary>
/// 发送失败次数
/// </summary>
public int ErrorCounter { get; set; }
/// <summary>
/// 发送失败错误信息
/// </summary>
public string ErrorMessage { get; set; }
}
public class MessageEmailAttachment
{
public Guid EmailAttachmentID { get; set; }
public Guid MessageEmailID { get; set; }
public string FileName { get; set; }
public byte[] FileData { get; set; }
}
}