Created
March 18, 2017 01:27
-
-
Save oscarkuo/e382e0d4111fb9e4258b73ffbb24f71b to your computer and use it in GitHub Desktop.
Code for sending an email with attachment via gmail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Net; | |
using System.Net.Mail; | |
using System.Net.Mime; | |
namespace SendViaGmail | |
{ | |
class Program | |
{ | |
static void SendEmail(SmtpClient smtp, MailAddress from, MailAddress to, string subject, string body, string attachmentPath) | |
{ | |
using (var message = new MailMessage(from, to) { Subject = subject, Body = body }) | |
{ | |
if (attachmentPath != null && File.Exists(attachmentPath)) | |
{ | |
var attachment = new Attachment(attachmentPath, MediaTypeNames.Application.Octet); | |
var disposition = attachment.ContentDisposition; | |
disposition.CreationDate = File.GetCreationTime(attachmentPath); | |
disposition.ModificationDate = File.GetLastWriteTime(attachmentPath); | |
disposition.ReadDate = File.GetLastAccessTime(attachmentPath); | |
disposition.FileName = Path.GetFileName(attachmentPath); | |
disposition.Size = new FileInfo(attachmentPath).Length; | |
disposition.DispositionType = DispositionTypeNames.Attachment; | |
message.Attachments.Add(attachment); | |
} | |
smtp.Send(message); | |
} | |
} | |
static void Main(string[] args) | |
{ | |
var from = new MailAddress("your.gmail.account@gmail.com", "From MailAddress"); | |
var destinations = new MailAddress[] | |
{ | |
new MailAddress("to0@theirdomain", "To0 MailAddress"), | |
new MailAddress("to1@theirdomain", "To1 MailAddress") | |
}; | |
const string password = "<YOUR GMAIL APP PASSWORD>"; | |
const string subject = "Test Subject"; | |
const string body = "Test Body"; | |
const string attachmentPath = @"d:\test.pdf"; | |
using (var smtp = new SmtpClient | |
{ | |
Host = "smtp.gmail.com", | |
Port = 587, | |
EnableSsl = true, | |
DeliveryMethod = SmtpDeliveryMethod.Network, | |
UseDefaultCredentials = false, | |
Credentials = new NetworkCredential(from.Address, password) | |
}) | |
{ | |
foreach (var destination in destinations) | |
{ | |
SendEmail(smtp, from, destination, subject, body, attachmentPath); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment