发送邮件
1创建一个名为”MailHelper.cs”的类(需要导入库using System.Net.Mail;),类的内容
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
namespace Demo1
{
class MailHepler
{
private string mailfrom;
private string[] mailtolist;
private string[] mailcclist;
private string mailsubject;
private string mailbody;
private string[] mailattachs;
private string host;
private bool mailbodyhtml = false;
public string From
{
get { return mailfrom; }
set { mailfrom = value; }
}
public string[] To
{
get { return mailtolist; }
set { mailtolist = value; }
}
public string[] CC
{
get { return mailcclist; }
set { mailcclist = value; }
}
public string Subject
{
get { return mailsubject; }
set { mailsubject = value; }
}
public string Body
{
get { return mailbody; }
set { mailbody = value; }
}
public string[] Attachments
{
get { return mailattachs; }
set { mailattachs = value; }
}
public string Host
{
get { return host; }
set { host = value; }
}
public string SendMail()
{
string str = “”;
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
msg.From = new MailAddress(mailfrom);
if (mailtolist != null)
{
if (mailtolist.Length > 0)
{
for (int i = 0; i < mailtolist.Length; i++)
{
if (!string.IsNullOrEmpty(mailtolist[i]))
{
msg.To.Add(mailtolist[i].Trim());
}
}
}
}
if (mailcclist != null)
{
if (mailcclist.Length > 0)
{
for (int i = 0; i < mailcclist.Length; i++)
{
if (!string.IsNullOrEmpty(mailcclist[i]))
{
msg.CC.Add(mailcclist[i].Trim());
}
}
}
}
msg.Subject = mailsubject;
msg.SubjectEncoding = System.Text.Encoding.UTF8;
msg.Body = mailbody;
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.IsBodyHtml = mailbodyhtml;
if (mailattachs != null)
{
if (mailattachs.Length > 0)
{
for (int i = 0; i < mailattachs.Length; i++)
{
if (!string.IsNullOrEmpty(mailattachs[i]))
{
msg.Attachments.Add(new Attachment(mailattachs[i].Trim()));
}
}
}
}
msg.Priority = MailPriority.Normal;//邮件优先级
SmtpClient client = new SmtpClient();
client.Host = host;// // 设置SMTP服务器地址
//NetworkCredential 类是为基于密码的身份验证方案(如基本、简要、NTLM 和 Kerberos)提供凭据的基类
client.Credentials = new System.Net.NetworkCredential("email", "emailPassword");//指定的用户名和密码
try
{
client.Send(msg);
//client.SendAsync(msg, userState);
//简单一点儿可以client.Send(msg);
msg.Dispose();
str = "Mail has send !";
}
catch (System.Net.Mail.SmtpException ex)
{
str = "Mail Error " + ex.ToString();
}
return str;
}
}
}
2调用MailHelper方法
MailHepler mmmm = new MailHepler();
mmmm.From = “FromEmail”;//发件人邮箱
mmmm.To = new string[] { “ToEmail1”, “ToEmail2” };//收件人邮箱组
mmmm.Host = “”;//client.Host = “smtp.qq.com”; 设置SMTP服务器地址
mmmm.Subject = “email subject”;
mmmm.Body = “email body”;
mmmm.SendMail();//发送邮件