Friday, July 31, 2009

How to send Emails with Gmail Account with Attachment

First you need to change the settings in your Gmail account

step 1: Login to your Gmail Account with from which you will be sending e-mails.

step 2: Go to Gmail settings then click on Forwarding and POP/IMAP

step 3: In IMAP Access Check Enable IMAP

step 4: Then go to your application use below code

void AttachFile(string attachmentFile)
System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress("");

System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("");
System.Net.Mail.MailMessage mm = new System.Net.Mail.MailMessage(fromAddress, toAddress);

mm.Subject = "Email Subject";
System.Net.Mail.Attachment mailAttachment = new System.Net.Mail.Attachment(printScreen);
mm.IsBodyHtml = true;

mm.BodyEncoding = System.Text.Encoding.UTF8;

How do I specify multiple recipients? Printer Friendly
Because the
To, CC, and Bcc properties are MailAddress collections, to add
additional recipients, all we need to do is call .Add(...) on the
respective properties.

Below is an example that demonstrates adding multiple To, CC, and Bcc addresses.

[ C# ]

static void MultipleRecipients()
//create the mail message
MailMessage mail = new MailMessage();

//set the addresses
//to specify a friendly 'from' name, we use a different ctor
mail.From = new MailAddress(""
, "Steve James");

//since the To,Cc, and Bcc accept addresses, we can use the same technique as the From address
//since the To, Cc, and Bcc properties are collections, to add multiple addreses, we simply call .Add(...) multple times

//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email.";

//send the message
SmtpClient smtp = new SmtpClient("");

string sendMail(System.Net.Mail.MailMessage mm)
string smtpHost = "";

string userName = "";//sending Id
string password = "your-password";
System.Net.Mail.SmtpClient mClient = new System.Net.Mail.SmtpClient();

mClient.Port = 587;
mClient.EnableSsl = true;
mClient.UseDefaultCredentials = false;
mClient.Credentials = new NetworkCredential(userName, password);

mClient.Host = smtpHost;
mClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
catch (Exception ex)


Have to replace \r\n with html line break "br"
in order to show paragraph and line breaks.
string sNewBody = textBoxBody.Text.Replace("\r\
n", "
//mm.Body = textBoxBody.Text;
mm.Body = sNewBody;

No comments: