
ตัวอย่าง Code ASP.NET (C#) สำหรับส่ง E-mail
protected void Page_Load(object sender, EventArgs e)
{
SendMail("ทดสอบส่ง E-mail จ้า");
}
public static bool SendMail(string gMailAccount, string password, string to, string subject, string message)
{
try
{
NetworkCredential loginInfo = new NetworkCredential(gMailAccount, password);
MailMessage msg = new MailMessage();
msg.From = new MailAddress(gMailAccount);
msg.To.Add(new MailAddress(to));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("mail.example.com"); //ระบุ SMTP
client.EnableSsl = false; // ต้องดูว่า Server ไหนใช้ SSL ปกติจะไม่ใช้แต่ยกเว้นพวกเซิฟเวอรที่ต้องการความปลอดภัยเพิ่ม
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
return true;
}
catch (Exception)
{
return false;
}
}
private void SendMail(string msg)
{
try
{
if (SendMail("E-mail ผู้ส่ง", "พาสเวริดของ E-mail ผู้ส่ง", "E-mail ผู้รับ", "ชื่อ Title E-mail", msg)) //msg คือรับค่าเนื้อหา Email เข้ามา
{
Response.Redirect("SendmailSuccess.aspx");// ถ้าส่งได้ให้ Redirect ไปหน้าไหน
}
else
{
Page.RegisterStartupScript("chkalert", "<script language='javascript'>alert('กรุณาตรวจสอบ Email');</script>");
}
}
catch (Exception ex)
{
}
}
ถ้าส่งเสร็จจะถูก Redirect ไปหน้า SendmailSuccess.aspx ถ้าส่งไม่ได้มันจะแจ้งว่ากรุณาตรวจสอบ E-mail ให้เช็คว่า smtp user แล้วก็ mode ของ client.EnableSsl ว่ากำหนดถูกไหม ถ้าทำถูกหมดก็จะสามารถส่ง E-mail ได้
