Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / system

Using Gmail Account to Send Emails With Attachment

4.71/5 (7 votes)
18 Apr 2011CPOL 14.7K  
Sending mail with attachmentspublic partial class Form1 : Form { public Form1() { InitializeComponent(); } public class MailClass : List { public void CreateMailAddresses(string sender, string reciever, out...
Sending mail with attachments

C#
public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public class MailClass : List<string>
        {
            public void CreateMailAddresses(string sender, string reciever, out MailAddress mailfrom, out MailAddress mailto)
            {
                MailAddress Mailfrom = new MailAddress(sender);
                MailAddress Mailto = new MailAddress(reciever);
                mailfrom = Mailfrom;
                mailto = Mailto;
            }

            public MailMessage MailMessage(MailAddress mailfrom, MailAddress mailto, string subject, string body)
            {
                MailMessage newmsg = new MailMessage(mailfrom, mailto);

                newmsg.Subject = subject;
                newmsg.Body = body;
                newmsg.IsBodyHtml = true;
                return newmsg;
            }

            public SmtpClient SmtpClient(string sender, string password, string host, bool SslEnabled, int port)
            {
                SmtpClient smtp = new SmtpClient(host, port);
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new NetworkCredential(sender, password);
                smtp.EnableSsl = SslEnabled;
                return smtp;
            }
        }
        MailClass Mail = new MailClass();
        private void button1_Click(object sender, EventArgs e)
        {
            
            MailAddress mailfrom;
            MailAddress mailto;
            Mail.CreateMailAddresses("sender@gmail.com", "reciever@ymail.com", out mailfrom, out mailto);
            MailMessage newmsg = Mail.MailMessage(mailfrom, mailto, "Subject of Email", "Body(message) of email");
            Byte google;
            for (google = 0; google < Mail.Count; google++)
            {
                newmsg.Attachments.Add(new Attachment(Mail[google]));
            }
            SmtpClient smtp = Mail.SmtpClient("sender@gmail.com", "password", "smtp.gmail.com", true, 587);
            smtp.Send(newmsg);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // add attachments
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.Cancel)
                return;
            Mail.Add(ofd.FileName);
        }
    }

License

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