今天有一个模块需要自动发送邮件的功能,就随便写了一个,记录一下作为积累。
一、首先需要配置web.config文件:
8 <system.net>
9 <mailSettings>
10 <smtp from="Emailname">
11 <network host="smtp.163.com" userName="Emailname" password="Emailpassword"
12 port="25" defaultCredentials="false"/>
13 </smtp>
14 </mailSettings>
15 </system.net>
16
17
34 //邮件发送人地址
35 System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(mailFrom);
36 //如test@163.com,初步测试,用test@sina.com不行,用163的邮件服务器,就必须用163邮箱的用户名
37 //收件人地址
38 System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(mailto);//如test@tom.com
39 System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(from, to);
40 mail.Subject = mailsubject;
41 mail.Body = mailbody;
42 //以下设置服务器
43 System.Net.Mail.SmtpClient mySmth = new System.Net.Mail.SmtpClient();
44 //以下为增加附件
45 int count = list.Count;
46 for (int i = 0; i < count; i++)
47 {
48 System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(list[i].ToString());
49 mail.Attachments.Add(data);
50 }
51 mySmth.Send(mail);
52 mail.Dispose();
53 return true;
54 }
55 catch
56 {
57 return false;
58 }
59}
60
61
62三、最后就是对函数的调用了:
63
64
65//自动发送邮件
66string mailSubject = "会员注册确认函";
67string mailBody = "正文内容。";
68string mailFrom = ConfigurationManager.AppSettings["SendMail"];
69ArrayList List = new ArrayList();
70List.Add(Server.MapPath(ConfigurationManager.AppSettings["SendMailText"]));
71if (MySendMail(this.txtEmail.Text, mailSubject, mailBody, mailFrom, List))
72{
73
74 //发送成功,进行相应处理
75}
76else
77{
78
79 //发送失败,进行相应处理
80 return;