您的位置:首页 > 编程语言 > C#

C#代码发送邮件

2016-07-14 11:05 633 查看
本次测试的邮箱为163邮箱

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



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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: