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("your-reciving-email@gmail.com");

System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress("fromAddress@yahoo.com");
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.Attachments.Add(mailAttachment);
mm.IsBodyHtml = true;

mm.BodyEncoding = System.Text.Encoding.UTF8;
sendMail(mm);
}

NOTE1:
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("me@mycompany.com"
, "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
mail.To.Add("you@yourcompany.com");
mail.To.Add("you2@yourcompany.com");
mail.CC.Add("cc1@yourcompany.com");
mail.CC.Add("cc2@yourcompany.com");
mail.Bcc.Add("blindcc1@yourcompany.com");
mail.Bcc.Add("blindcc2@yourcompany.com");

//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("127.0.0.1");
smtp.Send(mail);

string sendMail(System.Net.Mail.MailMessage mm)
{
try
{
string smtpHost = "smtp.gmail.com";

string userName = "your-email-address@gmail.com";//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;
mClient.Send(mm);
}
catch (Exception ex)

{
MessageBox.Show(ex.Message);
}
}
NOTE2

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: