今天學著寫了一個簡單的郵件發送程式,是用IIS的SMTP伺服器發送的(下一步學慣用Jmail組件發送),經測試後,成功向自己的郵箱發送了一封郵件。感覺挺有意思,希望自己以後能寫出類似於Foxmail的軟體,嗯,加油吧~~~
1、安裝SMTP服務
安裝此組件:'控制台'->'添加或刪除程式'->'添加或刪除Windows組件'->'應用程式伺服器'->'Internet資訊服務(IIS)'->SMTP Service
2、配置SMTP虛擬機器
在'控制項面板'->'管理工具'->'IIS管理器'->'預設SMTP虛擬伺服器'->'屬性'中,填寫原生IP地址,其他項視需要選擇。
3、設計郵件發送介面
收件者:tbReceiver
寄件者:tbSender
寄件者信箱使用者名:tbSenderUsername
寄件者郵箱密碼:tbSenderPsw
主題:tbSubject
內容:tbContent
附件:fuAttachment //fileUpload控制項
發送:btnSend
4、主要用System.Net.Mail中的類來編寫郵件發送程式
主要代碼如下:
//引入3個命名空間
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
protected void btnSend_Click(object sender, EventArgs e)
{
try
{
if (this.tbReceiver.Text != string.Empty && this.tbSender.Text != string.Empty)
{
//建立郵件
MailMessage myMail = new MailMessage(this.tbSender.Text.Trim(), this.tbReceiver.Text.Trim(), this.tbSubject.Text.Trim(), this.tbContent.Text.Trim());
myMail.Priority = MailPriority.High;
//建立附件
if (this.fuAttach.FileName!=null)
{
string filePath = this.fuAttachment.PostedFile.FileName;
FileInfo fi = new FileInfo(filePath);
if (fi.Exists)
{
Attachment myAttachment = new Attachment(filePath, MediaTypeNames.Application.Octet);
ContentDisposition disposition = myAttachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(filePath);
disposition.ModificationDate = File.GetLastWriteTime(filePath);
disposition.ReadDate = File.GetLastAccessTime(filePath);
myMail.Attachments.Add(myAttachment);
}
}
//發送附件
SmtpClient client = new SmtpClient("smtp.163.com", 25);
client.Credentials = new System.Net.NetworkCredential(this.tbUser.Text.Trim(), this.tbPsw.Text.Trim());
client.Send(myMail);
Response.Redirect("mailInfo.aspx"); //發送成功提示頁面
}
}
catch
{
Response.Write("<font color=red>郵件發送失敗!原因可能是:1)收件者地址不存在 2)寄件者地址不存在 3)使用者名稱或密碼錯誤</font>"); //錯誤資訊提示
}
finally
{ }
}