利用本機SMTP將信件寄出
參考了藍色小舖資料後
小小改寫一下
利用本機SMTP將信件寄出到指定的信箱。
函式說明:
利用本機SMTP寄送郵件
- /// <summary>
- /// 利用伺服器SMTP寄送郵件
- ///
- /// </summary>
- /// <param name="MailServer">The mail server.</param>
- /// <param name="Account">The account.</param>
- /// <param name="Password">The password.</param>
- /// <param name="FromMailAddress">From mail address.</param>
- /// <param name="toMailAddress">To mail address.</param>
- /// <param name="subject">The subject.</param>
- /// <param name="body">The body.</param>
- public static void SendMail(string FromMailAddress, string toMailAddress, string subject, string body)
- {
- System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("LocalHost");
- //指定 Smtp 伺服器
- smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
- //指定外送電子郵件的處理方式
- smtp.Credentials = new System.Net.NetworkCredential("","");
- //利用帳號/密碼取得 Smtp 伺服器的憑證
- System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
- //要發送的訊息
- msg.SubjectEncoding = System.Text.Encoding.Default;
- //主旨的編碼方式
- msg.BodyEncoding = System.Text.Encoding.Default;
- //訊息主體(郵件內容)的編碼方式
- msg.IsBodyHtml = false;
- //訊息主體(郵件內容)不要以 HTML 的方式呈現
- msg.From = new System.Net.Mail.MailAddress(FromMailAddress);
- //寄件者
- msg.To.Add(new System.Net.Mail.MailAddress(toMailAddress));
- //收件者
- msg.Subject = subject;
- //主旨
- msg.Body = body;
- //訊息主體(郵件內容)
- smtp.Send(msg);
- //發送 e-mail
- msg.Dispose();
- //釋放訊息所佔用的記憶體
- }
函式用法:
public static void SendMail(string FromMailAddress, string toMailAddress, string subject, string body)
C#:
- using System.Text;// StringBuilder要引用
- protected void Button1_Click(object sender, EventArgs e)
- {
- string subject = "TestEmail";
- string body = string.Empty;
- StringBuilder sb = new StringBuilder();
- sb.AppendLine("This is test mail");
- sb.AppendLine("Good Job!");
- body = sb.ToString();
- MailUtility.SendMail("aaa@www.com.tw", "ccc@ddd.com.tw", subject , body);
- //寄件者信箱 aaa@www.com.tw
- //收件者信箱 ccc@ddd.com.tw
- //主旨 TestEmail
- //內容 This is test mail
- // Good Job!
- }
VB:
- Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
- Dim subject As String = "TestEmail"
- Dim body As String = String.Empty
- Dim sb As New StringBuilder()
- sb.AppendLine("This is test mail")
- sb.AppendLine("Good Job!")
- body = sb.ToString()
- MailUtility.SendMail("aaa@www.com.tw", “ccc@ddd.com.tw”, subject, body)
- '寄件者信箱 aaa@www.com.tw
- '收件者信箱 ccc@ddd.com.tw
- '主旨 TestEmail
- '內容 This is test mail
- ' Good Job!
- End Sub
注意事項:
當畫面出現下列訊息
表示伺服器沒有開SMTP或者防火牆有檔,請去開啟服務
或者修改郵件伺服器主機。
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("LocalHost");
//指定 Smtp 伺服器為本機由於沒有提供SMTP所以會出現上列錯誤訊息
此外,需要確認smtp內容
轉接限制