Tuesday, September 9, 2008

VB.NET SMTP Send Mail

Occasionally I seem to find it hard to find how to do things which seem that they should be easy to find. So to make it easy for me to find in the future I will stick them in this blog.

Add a reference to MAPI.
This function sends a mail item with the sMsgBody string as the text of the message.
This is a fairly simple function it has lots of room for improvement but gives the basics of sending mail in .NET 7.1

Public Function SendMail(ByVal sMsgBody As String) As Boolean
Dim MyMail As Web.Mail.MailMessage = New System.Web.Mail.MailMessage
MyMail.From = sEmailFrom
MyMail.To = sEmailTo
MyMail.Subject = sEmailSubject
MyMail.Body = sMsgBody
MyMail.Cc = sEmailCc
MyMail.Bcc = sEmailBcc
MyMail.UrlContentBase = sUrlContentBase
MyMail.UrlContentLocation = sUrlContentLocation

MyMail.BodyEncoding = BodyEncoding
MyMail.BodyFormat = BodyFormat
MyMail.Priority = Priority

' Build an IList of mail attachments.
If sEmailAttachments <> "" Then
Dim delim As Char = ","
Dim sSubstr As String
For Each sSubstr In sEmailAttachments.Split(delim)
Dim myAttachment As MailAttachment = New MailAttachment(sSubstr)
MyMail.Attachments.Add(myAttachment)
Next
End If

Try
SmtpMail.SmtpServer = sEmailServer
SmtpMail.Send(MyMail)
Catch ex As Exception
sLastError = "Exception while sending mail: " & ex.Message
Return False
End Try

'lblMsg1.Text = "VB Message sent to " & MyMail.To ' or make this a MsgBox()
Return True
End Function

No comments: