C#代码发送邮件

时间:2021-10-30 04:40:55

本次测试的邮箱为163邮箱

1、首相对邮箱进行一些设置(详见下图);打开设置选取客户端授权密码项,开启设置;以后在客户端登录时将使用刚刚设置的密码!

C#代码发送邮件

2、上干货

  public static void TestEmail2()
{
try
{
//确定smtp服务器地址。实例化一个Smtp客户端
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient("smtp.163.com ");
//生成一个发送地址
string strFrom = string.Empty;
strFrom = "发送的邮箱@163.com";
//构造一个发件人地址对象
MailAddress from = new MailAddress(strFrom, "发件人", Encoding.UTF8);
//构造一个收件人地址对象 例如123456@qq.com
MailAddress to = new MailAddress("收件邮箱", "收件人", Encoding.UTF8);
//构造一个Email的Message对象
MailMessage message = new MailMessage(from, to);
//得到文件名
string fileName = @"附件文件地址";
//判断文件是否存在
if (File.Exists(fileName))
{
//构造一个附件对象
Attachment attach = new Attachment(fileName);
//得到文件的信息
ContentDisposition disposition = attach.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(fileName);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(fileName);
disposition.ReadDate = System.IO.File.GetLastAccessTime(fileName);
//向邮件添加附件
message.Attachments.Add(attach);
}
else
{
Log4Net.LogHelper.WriteLog(typeof(EmailService), "文件" + fileName + "未找到!");
}
//添加邮件主题和内容
message.Subject = "主题";
message.SubjectEncoding = Encoding.UTF8;
message.Body = "邮件内容";
message.BodyEncoding = Encoding.UTF8;
//设置邮件的信息
client.DeliveryMethod = SmtpDeliveryMethod.Network;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.IsBodyHtml = false; //gmail支持,163不支持,如果是gmail则一定要将其设为true
client.EnableSsl = false; //设置用户名和密码。
client.UseDefaultCredentials = false;
string username = "邮箱名(无163后缀)";
string passwd = "刚刚设置的客户端授权码";
//用户登陆信息
NetworkCredential myCredentials = new NetworkCredential(username, passwd);
client.Credentials = myCredentials;
//发送邮件
client.Send(message);
//提示发送成功
}
catch (Exception ex)
{
Log4Net.LogHelper.WriteLog(typeof(EmailService), ex.Message);
}
}