網上很多這樣的代碼,把所用到的類的介紹的很詳細,我在這裡就不在一一介紹。再這裡說借個錯誤的解決方案:
1. 0x80040217. The server response was not available
我用的sina的smtp服務,當開啟你的sina郵箱的pop/smtp服務之後,該錯誤就不存在了。
具體路徑:郵箱設定->賬戶->POP/SMTP設定->開啟
2. 530 Authentication required
那是沒提供你所用的郵件的使用者名稱和密碼
//基本許可權<br /> objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");</p><p> //使用者名稱<br /> objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "mytest110");</p><p> //密碼<br /> objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "mytest110");
所有代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Mail;
namespace MailSender
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
MailMessage objMailMessage;
MailAttachment objMailAttachment;
// 建立一個附件對象
objMailAttachment = new MailAttachment("C://1.xml");//發送郵件的附件
// 建立郵件訊息
objMailMessage = new MailMessage();
objMailMessage.From = "mytest110@sina.com";//源郵件地址
objMailMessage.To = "********@qq.com";//目的郵件地址
objMailMessage.Subject = "郵件發送標題:你好";//發送郵件的標題
objMailMessage.Body = "郵件發送標內容:測試一下是否發送成功!";//發送郵件的內容
objMailMessage.Attachments.Add(objMailAttachment);//將附件附加到郵件訊息對象中
//接著利用sina的SMTP來發送郵件,需要使用Microsoft .NET Framework SDK v1.1和它以上的版本
//基本許可權
objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
//使用者名稱
objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", "mytest110");
//密碼
objMailMessage.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", "******");
//如果沒有上述三行代碼,則出現如下錯誤提示:伺服器拒絕了一個或多個收件者地址。伺服器響應為:530 Authentication required
//SMTP地址
SmtpMail.SmtpServer = "smtp.sina.com";
// 開始發送郵件
// 在發送之前,去新浪郵箱裡開啟POP/SMTP設定 郵箱設定->賬戶->POP/SMTP設定->開啟
// 否則會報錯誤0x80040217. The server response was not available
SmtpMail.Send(objMailMessage);
}
}
}
PS:*號的地方設定自己的資料