Send Email Message with SMTP | | A common task in .NET is wanting to send someone a mail message. Thanks to System.Web.Mail, it's a piece of case.
First, add the using directive:
Next, declare an instance of the MailMessage class
MailMessage myMessage = new MailMessage();
Next, set whatever properties you want (I've included most of the more common ones):
myMessage.To = this.EmailAddress;
myMessage.From = Environment.UserName + "@knowdotnet.com";
myMessage.Priority = this.MessagePriority;
myMessage.Subject = String.Format("Message from {0} at {1}", this.From, this.Company);
StringBuilder sb = new StringBuilder();
sb.Append(To + ", you received a Message from " + From + " with " + this.Company + "\r\n\r\n");
sb.Append("at " + MessageDate + " " + MessageTime + "\r\n\r\n");
sb.Append("Regarding : " + this.Regarding + "\r\n\r\n");
sb.Append("They : " + this.PhoneActions + "\r\n\r\n");
sb.Append("They can be reached at : " + this.Phone + "\r\n\r\n");
sb.Append("Their Message: " + this.Message + "\r\n\r\n");
sb.Append("Initialed: " + Environment.UserName);
myMessage.Body = sb.ToString();
| Finally, call the SmtpMail.Send shared method, passing in your mail message:
try
{
SmtpMail.Send(myMessage);
}
catch(System.Exception ex)
{
Debug.Assert(false, ex.ToString());
} |
There is also another Constructor which takes in multiple string arguments like so:
SmtpMail.Send(From, To, Subject, Body);
|
In the example above:
| SmtpMail.Send(Environment.Username + "@knowdotnet.com", this.EmailAddress, this.Subject, this.Message); |
Where I had a class with EmailAddress, Subject and Message properties.
That's it!
|