Sonntag, 16. Dezember 2007

Sending e-mails with System.Net

Many programs call the default e-mail program for sending Mails. But what is if a user use an Webmail Account instead of Outlook, Live Mail, Windows Mail, Thunderbird or all the other mail clients? In many cases e-mail provider support sending e-mails via SMTP (the protocol also mostly is used by real mail clients). 

Know I will show you how to send a mail via .Net and how to attach files to your mails.

Every sting in the code samples could be replaced by a parameter added to the Send method.

Imports System.Net.Mail
Public Class SendMail
Public Shared Sub Send()
Dim message As New MailMessage("sender@servername", "from@servername", "Subject", "MessageText")

Dim emailClient As New SmtpClient("servername")
emailClient.Send(message)
End Sub
End
Class


That's the easiest way. This way does NOT work in most cases. As you see: No account name and account password was used. Which e-mail allows this? No serious one ;) 



In many cases it is useful to define a port which your SmtpClient uses. Normally it is Port 25.



So we are going to extend the code.



Imports System.Net.Mail
Public Class SendMail
Public Shared Sub Send()
Dim message As New MailMessage("sender@servername", "from@servername", "Subject", "MessageText")
message.IsBodyHtml = False

Dim emailClient As New SmtpClient("servername", 25)

emailClient.DeliveryMethod = SmtpDeliveryMethod.Network
emailClient.Credentials = New System.Net.NetworkCredential("username", "password")
emailClient.Send(message)
End Sub
End
Class



Additionally I set message.IsBodyHtml to false, because we are sending just plain text and emailClient's DelivertyMethod was set to Network.



If you replaced every sting in the sample with real data by doing this in the method itself or by using method parameter, now the code should work and you are able to send a mail.



Next step: attachments.



Imports System.Net.Mail
Public Class SendMail
Public Shared Sub Send()
Dim message As New MailMessage("sender@servername", "from@servername", "Subject", "MessageText")
message.IsBodyHtml = False

Dim emailClient As New SmtpClient("servername", 25)

emailClient.DeliveryMethod = SmtpDeliveryMethod.Network
emailClient.Credentials = New System.Net.NetworkCredential("username", "password")

Dim Attachment As New Attachment("Path to your file")
message.Attachments.Add(Attachment)

emailClient.Send(message)

End Sub
End
Class


As you see I just created an System.Net.Mail.Attachment object which constructor uses a parameter for the file I want to send. Then the Attachment is Added to the attachment Collection of our message.

Keine Kommentare: