第一步:
封装一个发送邮件的类:EmailHelper.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Configuration;
using System.Threading;
namespace Utilities {
public class EmailHelper {
private static MailMessage mailMessage;
private static SmtpClient smtpClient;
/// <summary>
/// 多线程发送邮件
/// </summary>
/// <param name="emailto">目标地址</param>
/// <param name="title">邮件标题</param>
/// <param name="body">邮件内容</param>
public static void SendThread(string emailto, string title, string body)
{
ParameterizedThreadStart ParStart = new ParameterizedThreadStart(ThreadMethod_EmailTo);
Thread myThread = new Thread(ParStart);
object o = title + "|" + body + "|" + emailto;
myThread.Start(o);
}
private static void ThreadMethod_EmailTo(object ParObject)
{
try
{
string emailto = "aaaa@163.com";//邮箱地址
string pwd = "xxxxxxxx";//邮箱密码
string host = "smtp.163.com";
string[] str = ParObject.ToString().Split('|');
string[] strArray = str[2].Split(',');
foreach (string s in strArray)
{
mailMessage = new MailMessage();
mailMessage.To.Add(s);
mailMessage.From = new System.Net.Mail.MailAddress(emailto);
mailMessage.Subject = str[0];
mailMessage.Body = str[1];
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
mailMessage.Priority = System.Net.Mail.MailPriority.Normal;
smtpClient = new SmtpClient();
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential(mailMessage.From.Address, pwd);//设置发件人身份的票据
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Host = host;
smtpClient.Send(mailMessage);
}
}
catch { }
}
}
}
如果要发送多个收件地址,需要将收件地址用逗号(,)分隔.
第二步:
调用发送邮件方法:
EmailHelper.SendThread("123456@163.com", "邮件标题", 邮件内容);
第三步:
对发件邮箱做一个配置,例如163邮箱:
1.开启这两个服务
2.如果不记得客户端授权密码,需要重置一下(此密码就是发送邮件代码中要配置的邮箱密码,此密码不是邮箱的登录密码)
重置完成后将重置好的客户端授权密码配置到代码中:
这时候去发送一封邮件试试吧!