[SMTP]
Sending a Simple E-Mail Message
เริ่มด้วยการใช้ ASP.net
using System.Net.Mail;
ทางนี้ขอเลือกภาษาเป็น C# ละกันนะคับ
อันดับแรก เราใส่ ปุ่ม Button ไว้สำหรับส่ง email
หลังจาก กดแล้ว ทาง VS.2005 จะสร้าง method ให้เราดังนี้
protected void Button1_Click1(object sender, EventArgs e)
{
}
หลังจากนั้น ให้เรา ใส่ code สำหรับการส่ง mail ลงไป เช่น
MailAddress from = new MailAddress("AR_TAE@hotmail.com");
// สร้าง from เก็บราชื่อ mail สำหรับคนส่ง mail MailAddress to = new MailAddress("AR_TAE@hotmail.com");
// สร้าง to เก็บรายชื่อ mail ปลายทาง MailMessage message = new MailMessage(from, to);
// สร้าง message เพื่อกำหนด รายละเอียดของ mail
message.Subject = txtTopic.Text;
// ส่วน subject
message.Body = txtComment.Text;
// ส่วน Body
message.BodyEncoding = System.Text.Encoding.ASCII;
// คำสั่ง ให้ body มีการ Encode แบบ ASCII
message.IsBodyHtml = true;
// คำสั่งอนุญาติให้ ข้อความที่ส่งไปสามารถใช้คำสั่ง html ได้
message.Priority = MailPriority.High;
// คำสั่งกำหนดความสำคัญของ email ฉบับนี้
try
{
SmtpClient client = new SmtpClient("localhost");
// เลือก server ที่จะทำการรับผิดชอบการส่ง email ฉบับนี้
client.Send(message);
// ใช้ client ที่กำหนดเมื่อกี้ ทำหน้าที่ส่ง message ที่ได้กำหนด
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
เป็นอันเสร็จสิ้น
ปัญหาก็คือ หลังจากส่ง แล้วมีการ Error mail Relay
ให้แก้ปัญหาโดยให้เข้าไปที่
1. Computer Management ใน control panel
2. แล้วเข้าไปที่ Services and Applications
3. ตามด้วย Internet Information Services
4. จะเห็น Default SMTP คลิกขวา properties
5. เลือก tab Access แล้วเลือกปุ่ม Relay..
6. จากนั้นจะปรากฏหน้า window Relay Restrictions
หลังจากทำตามจนได้ ดังรูปแล้ว
เข้าไป Run ใหม่ตาม code นี้ [code เดิมนั่นแหละ เอา comment ออกให้อ่านง่าย]
protected void Button1_Click1(object sender, EventArgs e)
{
MailAddress from = new MailAddress("AR_TAE@hotmail.com");
MailAddress to = new MailAddress("AR_TAE@hotmail.com");
MailMessage message = new MailMessage(from, to);
message.Subject = txtTopic.Text;
message.Body = txtComment.Text;
message.BodyEncoding = System.Text.Encoding.ASCII;
message.IsBodyHtml = true;
message.Priority = MailPriority.High;
try
{
SmtpClient client = new SmtpClient("Localhost");
client.Send(message);
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
}
}
ก็จะได้ mail มาแบบนี้
ปล. อันนี้ เปิดดูจาก C:\Inetpub\mailroot\Queue
ซึ่ง ไม่แน่ใจว่า ส่งได้จริงรึเปล่า เพราะเครื่องนี้ ยังไม่ได้ set outlook ยังไง หลาก็ไปลองดูหน่อยละกันนะ
ถ้าจะส่ง ไปยัง hotmail จิง ๆ เราต้อง Set SMTP ยังไงเนี่ยไม่รู้เหมือนกัน อ่ะคับ ถ้ามีอะไร update ก็จะมา update ให้ละกันนะคับ
CloveR
Ink Studio
[Empty Project]