Revision: 33709
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at October 12, 2010 13:52 by kyrathaba
Initial Code
1. private void button1_Click(object sender, EventArgs e) { 2. DialogResult dr = MessageBox.Show("Send email?", "Get Permission", MessageBoxButtons.YesNo, MessageBoxIcon.Question, 3. MessageBoxDefaultButton.Button2); 4. 5. if (dr == DialogResult.Yes) { 6. 7. SmtpClient smtpClnt = new SmtpClient("smtp.gmail.com", 587); 8. 9. try { 10. 11. MailMessage oMail = new MailMessage(); 12. oMail.To.Add(new MailAddress("[email protected]")); 13. oMail.From = new MailAddress("[email protected]"); 14. oMail.IsBodyHtml = true; 15. 16. oMail.Body = "your message body goes here"; 17. oMail.Subject = "your subject goes here"; 18. 19. smtpClnt.Timeout = 100000; 20. 21. smtpClnt.EnableSsl = true; 22. System.Net.NetworkCredential nc = new System.Net.NetworkCredential("[email protected]", "your_password"); 23. smtpClnt.Credentials = nc; 24. 25. Attachment oAttached = new Attachment("C:\\yourimage.jpg"); 26. oMail.Attachments.Add(oAttached); 27. 28. smtpClnt.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete); 29. 30. smtpClnt.SendAsync(oMail, "sending"); 31. 32. } 33. catch (Exception mailExc) { 34. if (mailExc.ToString().IndexOf("could not be resolved") >= 0) { 35. int line = mailExc.ToString().IndexOf("line"); 36. int leng = mailExc.ToString().Length; 37. string sLin = mailExc.ToString().Substring(line, (leng - line)); 38. string s = "Either the developer's Gmail SMTP was unavailable, or else your computer is not currently "; 39. s += "connected to the internet. Error generated at source code " + sLin; 40. MessageBox.Show(s, "Unable to send character file via email"); 41. } 42. else { 43. MessageBox.Show("Error:" + Environment.NewLine + Environment.NewLine + 44. mailExc.Message + Environment.NewLine + Environment.NewLine + mailExc.ToString()); 45. } 46. } 47. finally { 48. 49. //don't invoke smtpClnt.Dispose() here; if you do, the mail never sends 50. } 51. 52. 53. } 54. } 55. 56. 57. 58. private void MailDeliveryComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { 59. 60. string myMessage = e.ToString(); 61. string myCaption = string.Empty; 62. 63. if (e.Error != null) { 64. myCaption = "Error sending email"; 65. } 66. else if (e.Cancelled) { 67. myCaption = "Sending of email cancelled."; 68. } 69. else { 70. myCaption = "Your email message was sent successfully to the Game Master."; 71. } 72. 73. MessageBox.Show(myMessage, myCaption); 74. 75. }
Initial URL
Initial Description
Notes:\r\n\r\n(1) your namespace\'s using section should include the following:\r\nusing System.Net.Mail;\r\n\r\n(2) my example code places the email-sending code in a Button\'s Click() event-handler
Initial Title
Send Gmail email using C#
Initial Tags
Initial Language
C#