C# Code : Send Mail From your Application using your GMail Account
The code written below allows usrs to send mail from their application by using their GMail Account. The sent mail is also saved in sent mail folder of your GMail account. The mail is 100% legitimate. Try the code by changing just few things.
Write the code below in an event of a button which is to Sendmail
MailMessage mail = new MailMessage();
string username = usernametextBox.Text.ToString() + “@gmail.com”;
string password = passwordtextBox.Text.ToString();
string sendto = sendtotextBox.Text.ToString();
Attachment obje = new Attachment(attachmenttextBox.Text.ToString());
mail.Attachments.Add(obje);
string subject = subjecttextBox.Text.ToString();
mainmessage = mainmessagebody.Text.ToString();
mail.From = new MailAddress(username, usernametextBox.Text.ToString(), System.Text.Encoding.UTF8);
mail.To.Add(sendto);
mail.Subject = subject;
mail.SubjectEncoding = Encoding.UTF8;
mail.Priority = MailPriority.High;
mail.Body = mainmessage;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
mail.BodyEncoding = Encoding.UTF8;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential(username, password);
client.Port = 587;
client.Host = “smtp.gmail.com”;
client.EnableSsl = true;
client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
object userState = mail;
try
{
client.SendAsync(mail, userState);
}
catch (System.Net.Mail.SmtpException ex)
{
MessageBox.Show(ex.Message, “Send Mail Error”);
}
After this just add one event in your application in the same file
void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
MailMessage mail = (MailMessage)e.UserState;
string subject = mail.Subject;
if (e.Cancelled)
{
string cancelled = string.Format(”[{0}] Send canceled.”, subject);
MessageBox.Show(cancelled);
}
if (e.Error != null)
{
string error = String.Format(”[{0}] {1}”, subject, e.Error.ToString());
MessageBox.Show(error);
}
else
{
MessageBox.Show(”Your Mail has been sent.”);
Close();
}
}
So just us the code above by substituting the values of username, password, sendto, subject, body, attactments etc.
If you face any problem let me know.
Click here if you need a Website
very nice code help me alot