.net (c#)实现发送外部邮件的实例
using System;using System.Data;using System.Configuration;using System.Collections;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Net.Mail;public partial class testSendMail : System.Web.UI.Page{ protected void Page_Load(object sender, EventArgs e) { string strFrom = "xiaoxueli707325@126.com"; string strTo = "shirlly.liao@163.com"; string strSubject = "webtest"; string strBody = "测试"; System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(strFrom, strTo, strSubject, strBody); message.BodyEncoding = System.Text.Encoding.UTF8; message.IsBodyHtml = true; SendSMTPEMail("smtp.126.com", "xiaoxueli707325@126.com", "111111", message); } public void SendSMTPEMail(string strSmtpServer, string strFrom, string strFromPass, MailMessage message) { try { SmtpClient client = new SmtpClient(strSmtpServer); client.UseDefaultCredentials = true; client.Credentials = new System.Net.NetworkCredential(strFrom, strFromPass); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Send(message); } catch (Exception ex) { throw new Exception(ex.Message); } }}
注意:
1、确保strFrom的值和strSmtpServer的值一致,否之会报Send Error:不允许使用邮箱名称。 服务器响应为: You are not authorized to send mail, authentication is required。的错误
2、确保用于发送邮件的邮箱不是刚注册的邮箱,而要用有提供SMTP服务的邮箱的帐号和密码,否则会报邮箱不可以用的错误
client.UseDefaultCredentials = true;client.Credentials = new System.Net.NetworkCredential(strFrom, strFromPass);
否则会报这样的错误
引用
Send Error:不允许使用邮箱名称。 服务器响应为: You are not authorized to send mail, authentication is required。就是说没有通过登录认证
4、注意126的域名是smtp.126.com
163的域名是smtp.163.com