Sending Email in C# through Gmail

C#

Public Domain

Download (right click, save as, rename as appropriate)

Embed

Tags:

email gmail smtp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Net;
using System.Net.Mail;

namespace DomenicDenicola
{
    public class GmailSample
    {
        public static void Main()
        {
            var fromAddress = new MailAddress("from@gmail.com", "From Name");
            var toAddress = new MailAddress("to@example.com", "To Name");
            const string fromPassword = "fromPassword";
            const string subject = "Subject";
            const string body = "Body";

            // This sends email using the credentials fromAddress, fromPassword.
            var smtp = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network, // It is unclear for which setups this is needed; it's not needed in mine, but someone else reports that it is for theirs.
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body
            })
            {
                smtp.Send(message);
            }

            // This sends email from the given address, but notice how it doesn't require a password.
            // This will _only_ work when sending from a Gmail address to a Gmail address!
            var smtp2 = new SmtpClient("gmail-smtp-in.l.google.com");
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body
            })
            {
                smtp2.Send(message);
            }
        }
    }
}