Monday, April 23, 2012

SMTP Send Mail - example


MailMessage represents an e-mail message that can be sent using the SmtpClient class. Using MailMessage we can integrate auto mail feature where we have an SMTP client already available. 
Following is the sample mail implementation where subject and mail body passed as parameter. We can pass the MailAddress for sender and recipient as well.

Sample Code:
public bool Send_Mail(string csSubject, string csBody)
{
    MailAddress from = new MailAddress("aaa@abc.com", "aaa bbb");
    MailAddress to = new MailAddress("ccc@abc.com", "ccc ddd");
    MailMessage mMail = new MailMessage(from, to);
    mMail.Bcc.Add(from);
    mMail.Subject = "Test Subject";
    mMail.Body = csBody;
    mMail.IsBodyHtml = true;
    mMail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
    mMail.ReplyTo = from;

    SmtpClient client = new SmtpClient("xxx-exg99.xxxx.xx.com");
    client.Credentials = CredentialCache.DefaultNetworkCredentials;

    try
    {
        client.Send(mMail);
    }
    catch (Exception exc)
    {
        MessageBox.Show(exc.Message, "Not able to send mail", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        mMail.Dispose();
        return false;
    }
    mMail.Dispose();
    return true;
}

No comments:

Post a Comment