ส่ง E-mail ง่าย ๆ ด้วย class MailMessage และ SmtpClient

/ January 29th, 2010/ Posted in Computer, Programming, VB.NET/C# / 8 Comments »

     วันนี้เราจะมานำเสนอวิธีการส่ง E-mail ง่าย ๆ โดยการใช้ class MailMessage และ SmtpClient 
โดยการส่งเมล์นี้จะใช้ Protocol SMTP ในการส่ง 

1.การประกาศตัวแปลของ Object MailMessage
Dim mailClient As New MailMessage 

2.การกำหนด E-mail ผู้ส่ง
 mailClient.From = New MailAddress(address Asstring)
Ex. 
mailClient.From =New MailAddress(“Bill_Gate@hotmail.com“) 

3.การใส่ E-mail Address ปลายทาง 
mailClient.To.Add(address Asstring)
Ex.
mailClient.To.Add(“steve_job@apple.com) 

4การใส่ Suject และ Body
mailClient.Subject = subject
mailClient.Body = body
 

5.การประกาศตัวแปรของ SmtpClient
Dim sendMail As New SmtpClient(“Mail Server”, port)
“Mail Server” คือ Host SMTP ที่เราจะให้เค้าส่ง Mail ไปใช้
port Default คือ 25
sendMail.Credentials = New NetworkCredential(“Username”, “Password”)sendMail.Send(mailClient) 

6.การกำหนด Username และ Password สำหรับ login ไปยัง SMTP Mail Server 

7.จากนัน้ก็ส่งได้เลยครับ สบาย ๆ ฮ่า ๆ 

  

ข้างล่างเขียนเป็น COde ง่าย ๆ เอาไปลองใช้กันดูนะครับ 

  

  

Private Sub sendMail(ByVal from As String, ByVal sendTo As String, ByVal bcc As String, ByVal cc As String, ByVal subject As String, ByVal body As String)
Try
Dim mailClient As New MailMessage
Dim sendMail As New SmtpClient(“mail.com”, 25)

mailClient.From = New MailAddress(from)
mailClient.To.Add(New MailAddress(sendTo))
If bcc <> “” Then
mailClient.Bcc.Add(New MailAddress(bcc))
End If

If cc <> “” Then
mailClient.CC.Add(New MailAddress(bcc))
End If

mailClient.Subject = subject
mailClient.Body = body

mailClient.IsBodyHtml = True
mailClient.Priority = MailPriority.High

sendMail.Credentials = New NetworkCredential(“”, “”)
sendMail.Send(mailClient)
Console.WriteLine(“Send To sendTo OK”)


Catch ex As Exception
Console.WriteLine(“Send Mail Failed : ” & ex.ToString())
End Try
End Sub

   

 

 

 


Tags: , , ,

Leave a Reply

You must be logged in to post a comment.