Saturday, May 11, 2013

Sending email with attachments using C# and Gmail

Sending email with .Net is far simpler than it is in Delphi (using Indy).

Put the following in your classe's "using" section:
using System.Net.Mail;
using System.Net;

Include this method in your class

        private bool SendViaGmail()
        {
            try
            {
                var client = new SmtpClient("smtp.gmail.com", 587)
                {
                    Credentials = new NetworkCredential("myusername@gmail.com", "mypassword"),
                    EnableSsl = true
                };
                var msg = new MailMessage("myusername@gmail.com",
                    "mybuddy@example.com",
                    "Email subject",
                    "This is the email body...");
                msg.Attachments.Add(new Attachment("1.txt"));
                msg.Attachments.Add(new Attachment("2.jpg"));
                client.Send(msg);
                return true;
            }
            catch
            {
                return false;
            }
        }

No comments:

Post a Comment