Click here to Skip to main content
15,881,839 members
Articles / Programming Languages / C#
Tip/Trick

Sending Email with Custom Control

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
9 Jul 2011CPOL 12.9K   5   3
Sending Email with Custom Control
This is a simple Control that will enable you to send email messages. Just add this as a class to your project, build the solution, drop the control onto your form, then you can access the Methods and Properties from the Properties window. 

C#
namespace Email
{
    using System;
    using System.Drawing;
    using System.Net;
    using System.Net.Mail;
    using System.Windows.Forms;
    using System.ComponentModel;
    using System.Collections.Generic;
   
    [DefaultEvent("Click")]    
    public class MassMailer : Control
    {       
        private SizeF textSize;
        private List<String> recipents = new List<String>();
        private List<String> attachments = new List<string>();
        private Int32 port = 587;
        private Int32 timeout = 5000;
        private String sender = "youremail@mailaddress.com";
        private String password = "your email password here";
        private String subject = "Subject of MailMessage goes here";
        private const String StringCollectionEditor = "System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
        private String message = "Message to be sent";
        private String host = "smtp.gmail.com";
        private Boolean enableSsl = true;
        private Boolean useDefaultCredentials = false;
        private Boolean isBodyHtml = true;
        private SmtpDeliveryMethod method = SmtpDeliveryMethod.Network;
        private DeliveryNotificationOptions options = DeliveryNotificationOptions.OnFailure;
        private MailPriority priority = MailPriority.Normal;
        public MassMailer()
        {
            using (Graphics surface = this.CreateGraphics())
            {
                textSize = surface.MeasureString(" " + this.Text + " ", this.Font);
            }
            this.Width = (int)textSize.Width;
            this.Paint += new PaintEventHandler(MassMailer_Paint);
            this.TextChanged += new EventHandler(MassMailer_TextChanged);
            this.ForeColorChanged += new EventHandler(MassMailer_ForeColorChanged);
        }
        private void MassMailer_ForeColorChanged(object sender, EventArgs e)
        {
            this.Paint += new PaintEventHandler(MassMailer_Paint);
        }
        private void MassMailer_TextChanged(object sender, EventArgs e)
        {
            using (System.Drawing.Graphics surface = this.CreateGraphics())
            {
                textSize = surface.MeasureString(" " + this.Text + " ", this.Font);
            }
            this.Width = (int)textSize.Width;
            this.Paint += new PaintEventHandler(MassMailer_Paint);
        }
        private Int32 ControlWidth
        {
            get { return this.DisplayRectangle.Width - 1; }            
        }
        private Int32 ControlHeight
        {
            get { return this.DisplayRectangle.Height - 1; }
        }
        private void MassMailer_Paint(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(this.BackColor);
            e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), new PointF(1, textSize.Height / 2));
            e.Graphics.DrawRectangle(new Pen(new SolidBrush(this.ForeColor)), new Rectangle(0, 0, ControlWidth, ControlHeight));
        }
        [Description("List of recipents to recieve E-mail message.")]
        [Editor(StringCollectionEditor, typeof(System.Drawing.Design.UITypeEditor))]
        public List<String> RecipentList { get { return recipents; } set { recipents = value; } }
        
        [Description("List of attachments to send in E-mail.")]
        [Editor(StringCollectionEditor, typeof(System.Drawing.Design.UITypeEditor))]
        public List<string> AttachmentCollection { get { return attachments; } set { attachments = value; } }
 
        [Description("SMTP-Client E-mail port. Default is 587."), DefaultValue(587)]
        public Int32 Port { get { return port; } set { port = value; } }
        [Description("Amount of time after send message is called to timeout. Default is 5000.")]
        public Int32 Timeout { get { return timeout; } set { timeout = value; } }
        [Description("E-mail address of person sending E-mail.")]
        public String Sender { get { return sender; } set { sender = value; } }
        [Description("Password of person sending E-mail.")]
        public String Password { get { return password; } set { password = value; } }
        [Description("Subject of E-mail being sent.")]
        public String Subject { get { return subject; } set { subject = value; } }
               
        [Description("Message to send in E-mail.")]
        public String Body { get { return message; } set { message = value; } }
                
        [Description("SMTP-Client E-mail host. Default is smtp.gmail.com.")]
        public String Host { get { return host; } set { host = value; } }
               
        [Description("Determines if SMTP-Client is to use Secure Sockets Layer(Ssl) to Encrypt the connection. Default is true.")]
        public Boolean EnableSsl { get { return enableSsl; } set { enableSsl = value; } }
        
        [Description("Controls wheteher the System.Net.CredentialCache.DefaultCredentials are sent with request. Default is false")]
        public Boolean UseDefaultCredentials { get { return useDefaultCredentials; } set { useDefaultCredentials = value; } }
                
        [Description("Determines whether the E-mail message being sent is in Html. default is true.")]
        public Boolean IsBodyHtml { get { return isBodyHtml; } set { isBodyHtml = value; } }
        [Description("Specifies how E-mail messages are Delivered. Default is Network.")]
        public SmtpDeliveryMethod DeliveryMethod { get { return method; } set { method = value; } }
               
        [Description("Describes the delivery notification options for E-mail. Default is OnFailure.")]
        public DeliveryNotificationOptions NotificationOptions { get { return options; } set { options = value; } }
                
        [Description("Specifies the Priority of the E-mail message. Default is Normal.")]
        public MailPriority Priority { get { return priority; } set { priority = value; } }       
               
        public void SendMail()
        {
            this.Cursor = Cursors.WaitCursor;
            for (int X = 0; X < RecipentList.Count; X++)
            {
                using (MailMessage mMessage = new MailMessage(Sender, RecipentList[X], Subject, Body))
                {                    
                    for (int x = 0; x < AttachmentCollection.Count; x++)
                    {
                        mMessage.Attachments.Add(new Attachment(AttachmentCollection[x]));
                    }
                    mMessage.IsBodyHtml = IsBodyHtml;
                    mMessage.DeliveryNotificationOptions = NotificationOptions;
                    mMessage.Priority = Priority;
                    using (SmtpClient mailClient = new SmtpClient(Host, Port))
                    {                       
                        mailClient.EnableSsl = EnableSsl;
                        mailClient.Timeout = Timeout;
                        mailClient.UseDefaultCredentials = UseDefaultCredentials;
                        mailClient.DeliveryMethod = DeliveryMethod;
                        mailClient.Credentials = new NetworkCredential(Sender, Password);
                        mailClient.Send(mMessage);
                    }
                    this.Cursor = Cursors.Default;
                }
            }
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I do not claim to be wrong! I just rarely ever write.

Comments and Discussions

 
GeneralEdit: removed span formatting around narrative. Pin
DaveAuld9-Jul-11 1:00
professionalDaveAuld9-Jul-11 1:00 
GeneralRe: thanks but no thanks got it fixed Pin
charles henington9-Jul-11 14:06
charles henington9-Jul-11 14:06 
QuestionScreenshot? Pin
tlhIn`toq12-Jul-11 6:43
tlhIn`toq12-Jul-11 6:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.