1. Denver Ivan Gazo
  2. EE-Mass-Mailer

Source

EE-Mass-Mailer / EE_Mass_Mailer / Sender.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net;
using System.Xml;
using System.Web;
using System.Diagnostics;

namespace EE_Mass_Mailer
{
    public partial class Sender : Form
    {
        #region Fields

        SmtpClient client;
        int currentMember = 0;
        XmlDocument xmldoc;
        XmlNodeList members;
        const string sendingstr = "Sending {0} of {1} E-Mails";
        const string resendstr = "Resending mail {0}";

        enum SendType
        {
            Send,
            Resend
        }

        #endregion

        #region Constructor

        public Sender()
        {
            InitializeComponent();
            SendButton.Click += new EventHandler(SendButton_Click);
            this.Load += new EventHandler(Sender_Load);
        }

        void Sender_Load(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.password == "" || Properties.Settings.Default.username == "")
            {
                MessageBox.Show("You forgot to set your gmail username and password in the settings page.",
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Close();
            }
            
            loadXml();
        }

        #endregion

        void SendButton_Click(object sender, EventArgs e)
        {
            if (SendButton.Text == "Send")
            {
                SendButton.Text = "Cancel";
                startSend();
            }
            else
            {
                SendButton.Text = "Send";
                client.SendAsyncCancel();
            }
        }

        /// <summary>
        /// Parse the E-mail XML file.
        /// </summary>
        void loadXml()
        {
            xmldoc = new XmlDocument();
            //xmldoc.LoadXml(Properties.Resources.EE_Members);
            xmldoc.LoadXml(Properties.Resources.test_file);
            members = xmldoc.GetElementsByTagName("row");
        }

        /// <summary>
        /// Start sending mail
        /// </summary>
        void startSend(SendType type = SendType.Send)
        {
            // Initialize SMTP Client
            client = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(Properties.Settings.Default.username,
                    Properties.Settings.Default.password)
            };

            // Bind the Send Completion Event
            client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);

            string toEmail = members[currentMember]["email"].InnerText;
            string username = HttpUtility.HtmlDecode(members[currentMember]["name"].InnerText);
            string displayName = HttpUtility.UrlDecode(members[currentMember]["members_seo_name"].InnerText);
            string subject = SubjectTextBox.Text;
            // Replace instances of <username> and <display_name> in message body
            string message = MessageTextBox.Text.Replace("<username>", username).Replace("<display_name>", displayName);

            var mailmsg = new MailMessage(Properties.Settings.Default.username, toEmail)
                            {
                                Subject = subject,
                                Body = message,
                                BodyEncoding = Encoding.UTF8
                            };

            // Try Sending mail
            try
            {
                client.SendAsync(mailmsg, username);   
            }
            catch (SmtpFailedRecipientException ex)
            {
                Debug.Print(ex.GetType().ToString());
            }
            finally
            {
                updateStatus(type);
            }
            
        }

        /// <summary>
        /// Update status bar
        /// </summary>
        /// <param name="type"></param>
        void updateStatus(SendType type)
        {
            switch (type)
            {
                case SendType.Send:
                    StatusLabel.Text = String.Format(sendingstr, currentMember + 1, members.Count);
                    break;
                case SendType.Resend:
                    StatusLabel.Text = String.Format(resendstr, currentMember + 1);
                    break;
            }
        }

        /// <summary>
        /// Update the status bar
        /// </summary>
        /// <param name="str">Text to write on the status bar</param>
        void updateStatus(string str)
        {
            StatusLabel.Text = str;
        }

        /// <summary>
        /// Function that gets called after the SendAsync() call is done
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            Debug.WriteLine("Send Completed Called");


            if (e.Cancelled)
            {
                return;
            }

            if (e.Error != null)
            {
                startSend(SendType.Resend);
            }
            else
            {
                if (currentMember < members.Count)
                {
                    currentMember++;
                    startSend();
                }
                else
                {
                    updateStatus("Sending Complete");
                }
            }

        }
    }
}