C#发送邮件DEMO
虽然网上有很多类似的DEMO,但是还是整个封装好的例子,以便以后用;
发送邮箱是直接在web.config配置的。
protected void Button1_Click(object sender, EventArgs e) {
string mailto = "843935025@qq.com";
string mailSubject = "C#邮件测试";
string mailBody = "C#邮件测试成功";
string mailFrom = ConfigurationManager.AppSettings["FromMail"];
if (MySendMail(mailto, mailSubject, mailBody, mailFrom)) {
Error.Text="发送成功!";
}
else {
Error.Text = "发送失败!";
}
}
public bool MySendMail(string mailto, string mailsubject, string mailbody, string mailFrom) {
try {
System.Net.Mail.MailAddress from = new System.Net.Mail.MailAddress(mailFrom);//邮件发送人地址
System.Net.Mail.MailAddress to = new System.Net.Mail.MailAddress(mailto);//收件人地址
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(from, to);//邮件对象
message.Subject = mailsubject;
message.Body = mailbody;
System.Net.Mail.SmtpClient mySmth = new System.Net.Mail.SmtpClient();//设置服务器
mySmth.Send(message);//发送邮件
message.Dispose();
return true;
}
catch { return false; }
}
web.config
<appSettings>
<add key="FromMail" value="wust_chenlei@163.com"/>
</appSettings>
<system.net>
<mailSettings>
<smtp from="Emailname">
<network host="smtp.163.com" userName="wust_chenlei@163.com" password="cl19911111" port="25" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.net>