[Sample of Apr 25th] How to send email at particular date and time - Microsoft All-In-One Code Framework - Site Home - MSDN Blogs
Microsoft All-In-One Code Framework - Developers' Pain Killer

[Sample of Apr 25th] How to send email at particular date and time

Rate This
  • Comments 1

 

Homepage image
Sample of the Day RSS Feed

Sample Downloads: http://code.msdn.microsoft.com/CSEmailScheduler-21564366

Today’s code sample demonstrates how to send email at particular date and time; it also shows how to send emails in synchronous and asynchronous manner.

The sample was written by Microsoft engineer: Ajay Pathak.

imageYou can find more code samples that demonstrate the most typical programming scenarios by using Microsoft All-In-One Code Framework Sample Browser or Sample Browser Visual Studio extension. They give you the flexibility to search samples, download samples on demand, manage the downloaded samples in a centralized place, and automatically be notified about sample updates. If it is the first time that you hear about Microsoft All-In-One Code Framework, please watch the introduction video on Microsoft Showcase, or read the introduction on our homepage http://1code.codeplex.com/.

 

Introduction

CSEmailScheduler enables you to send email at particular date and time; it also shows how to send emails in synchronous and asynchronous manner.

 

Building the Sample

To build this sample

  1. Open CSEmailScheduler.sln file in Visual Studio 2010
  2. Build the Solution

 

Running the Sample

For running this sample, please follow the steps below:

1. Add SMTP configuration details in app.config file. Some of the popular SMTP settings can be found here

 

SMTP Server

Username

Password

Port

TLS/SSL

Hotmail

smtp.live.com

me@hotmail.com  or me@live.com

Hotmail password

587

Yes

Gmail

smtp.gmail.com

me@gmail.com

Gmail Password

Port for TLS/STARTTLS: 587
Port for SSL: 465

Yes

2. In Program.cs, you should replace the receiver’s E-Mail address with yours

// Receiver’s E-Mail address. 
mailMessage.To.Add("pathakajay@live.com");

3. Create a task in Windows Task Scheduler. For creating a Schedule a Task, please refer: http://technet.microsoft.com/en-us/library/cc748993.aspx article.

Using the Code

The following code snippet shows the key code for sending email.

public class EmailSender 
{ 
    /// <summary> 
    /// Send Email to a list of recipients.  
    /// </summary> 
    /// <param name="recipientList">A List of MailMessage object, that contains the list of Email Message</param> 
    /// <returns>Returns True, if e-mail is sent successfully otherwise false</returns> 
    public bool SendEmail(List<MailMessage> recipientList) 
    { 
        SmtpClient smtpClient = null; 
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
        var mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; 
        bool status = false; 
        try 
        { 
            // SMTP settings are defined in app.config file 
            smtpClient = new SmtpClient(); 
            foreach (MailMessage mailMessage in recipientList) 
            { 
                smtpClient.Send(mailMessage); 
            } 
 
 
            status = true; 
        } 
        catch (Exception e) 
        { 
            string errorMessage = string.Empty; 
            while (e != null) 
            { 
                errorMessage += e.ToString(); 
                e = e.InnerException; 
            } 
            status = false; 
 
 
        } 
        finally 
        { 
            if (smtpClient != null) 
            { 
                smtpClient.Dispose(); 
            } 
        } 
        return status; 
    } 
 
 
    /// <summary> 
    /// Asynchronously send Email to a list of recipients.  
    /// </summary> 
    /// <param name="recipientList">A List of MailMessage object, that contains the list of Email Message</param> 
    public void SendEmailAsync(List<MailMessage> recipientList) 
    { 
        SmtpClient smtpClient = null; 
        var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
        var mailSettings = config.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup; 
        object userState = null; 
        try 
        { 
            // SMTP settings are defined in app.config file 
            smtpClient = new SmtpClient(); 
            foreach (MailMessage mailMessage in recipientList) 
            { 
                userState = mailMessage; 
                smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted); 
                smtpClient.SendAsync(mailMessage, userState); 
            } 
        } 
        catch (Exception e) 
        { 
            string errorMessage = string.Empty; 
            while (e != null) 
            { 
                errorMessage += e.ToString(); 
                e = e.InnerException; 
            } 
        } 
        finally 
        { 
            if (smtpClient != null) 
            { 
                smtpClient.Dispose(); 
            } 
        } 
    } 
 
 
    void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) 
    { 
        // Get the Original MailMessage object 
        MailMessage mailMessage = (MailMessage)e.UserState; 
        string subject = mailMessage.Subject; 
 
 
        // Write custom logging code here. Currently it is showing error on console. 
        if (e.Cancelled) 
        { 
            Console.WriteLine("Send canceled for [{0}] with subject [{1}] at [{2}].", mailMessage.To, subject, DateTime.Now.ToString()); 
        } 
        if (e.Error != null) 
        { 
            Console.WriteLine("An error {1} occurred when sending mail [{0}] to [{2}] at [{3}] ", subject, e.Error.ToString(), mailMessage.To, DateTime.Now.ToString()); 
        } 
        else 
        { 
            Console.WriteLine("Message [{0}] is sent to [{1}] at [{2}].", subject, mailMessage.To, DateTime.Now.ToString()); 
        } 
    } 
} 

 

More Information

Schedule a Task: http://technet.microsoft.com/en-us/library/cc748993.aspx

SmtpClient Class: http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx

Leave a Comment
  • Please add 1 and 8 and type the answer here:
  • Post
  • I get this error:

    Send canceled for [rossmason@shelbysys.com] with subject [Send Email OneCode Sam

    ple] at [5/14/2012 8:26:16 AM].

    Message [Send Email OneCode Sample] is sent to [rossmason@shelbysys.com] at [5/1

    4/2012 8:26:16 AM].

    Nor sure what is cancelling the send byt teh email  never shows up.

Page 1 of 1 (1 items)