1 public static class Email
2 {
3 /// <summary>
4 /// 发件人
5 /// </summary>
6 public static string mailFrom { get; set; }
7
8 /// <summary>
9 /// 收件人
10 /// </summary>
11 public static string[] mailToArray { get; set; }
12
13 /// <summary>
14 /// 抄送
15 /// </summary>
16 public static string[] mailCcArray { get; set; }
17
18 /// <summary>
19 /// 标题
20 /// </summary>
21 public static string mailSubject { get; set; }
22
23 /// <summary>
24 /// 正文
25 /// </summary>
26 public static string mailBody { get; set; }
27
28 /// <summary>
29 /// 发件人密码
30 /// </summary>
31 public static string mailPwd { get; set; }
32
33 /// <summary>
34 /// SMTP邮件服务器
35 /// </summary>
36 public static string host { get; set; }
37
38 /// <summary>
39 /// 邮件服务器端口
40 /// </summary>
41 public static int port { get; set; }
42
43 /// <summary>
44 /// 正文是否是html格式
45 /// </summary>
46 public static bool isbodyHtml { get; set; }
47
48 /// <summary>
49 /// 附件
50 /// </summary>
51 public static string[] attachmentsPath { get; set; }
52
53 public static bool Send()
54 {
55 //使用指定的邮件地址初始化MailAddress实例
56 MailAddress maddr = new MailAddress(mailFrom);
57
58 //初始化MailMessage实例
59 MailMessage myMail = new MailMessage();
60
61 //向收件人地址集合添加邮件地址
62 if (mailToArray != null)
63 {
64 for (int i = 0; i < mailToArray.Length; i++)
65 {
66 myMail.To.Add(mailToArray[i].ToString());
67 }
68 }
69
70 //向抄送收件人地址集合添加邮件地址
71 if (mailCcArray != null)
72 {
73 for (int i = 0; i < mailCcArray.Length; i++)
74 {
75 myMail.CC.Add(mailCcArray[i].ToString());
76 }
77 }
78 //发件人地址
79 myMail.From = maddr;
80
81 //电子邮件的标题
82 myMail.Subject = mailSubject;
83
84 //电子邮件的主题内容使用的编码
85 myMail.SubjectEncoding = Encoding.UTF8;
86
87 //电子邮件正文
88 myMail.Body = mailBody;
89
90 //电子邮件正文的编码
91 myMail.BodyEncoding = Encoding.Default;
92
93 //电子邮件优先级
94 myMail.Priority = MailPriority.High;
95
96 //电子邮件不是html格式
97 myMail.IsBodyHtml = isbodyHtml;
98
99 //在有附件的情况下添加附件
100 try
101 {
102 if (attachmentsPath != null && attachmentsPath.Length > 0)
103 {
104 Attachment attachFile = null;
105 foreach (string path in attachmentsPath)
106 {
107 attachFile = new Attachment(path);
108 myMail.Attachments.Add(attachFile);
109 }
110 }
111 }
112 catch (Exception err)
113 {
114 throw new Exception("在添加附件时有错误:" + err.Message);
115 }
116
117 SmtpClient client = new SmtpClient();
118
119 //指定发件人的邮件地址和密码以验证发件人身份
120 client.Credentials = new NetworkCredential(mailFrom, mailPwd);
121
122 //设置SMTP邮件服务器
123 //client.Host = "smtp." + myMail.From.Host;
124 client.Host = host;
125
126 //SMTP邮件服务器端口
127 client.Port = port;
128
129 //是否使用安全连接
130 //client.EnableSsl = true;
131
132 try
133 {
134 //将邮件发送到SMTP邮件服务器
135 client.Send(myMail);
136 return true;
137 }
138 catch (SmtpException ex)
139 {
140 string msg = ex.Message;
141 return false;
142 }
143
144 }