And since I've shown how to
check Gmail using C# and Gmail's IMAP, the following snippet shows how to
send an email programmatically, through your Gmail account, using C# and Gmail's SMTP. Please note that, although the code doesn't require notification to the user that an email is about to be sent, you should
always notify the end-user of your program, and give him/her the
option of whether or not to send the email. If you don't, their firewall or protective software may scare them when it pops up a message about your program attempting to send email.
Notes:
(1) your namespace's
using section should include the following:
using System.Net.Mail;(2) my example code places the email-sending code in a Button's Click() event-handler
private void button1_Click(object sender, EventArgs e) {
DialogResult dr = MessageBox.Show("Send email?", "Get Permission", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
if (dr == DialogResult.Yes) {
SmtpClient smtpClnt
= new SmtpClient
("smtp.gmail.com",
587);
try {
MailMessage oMail
= new MailMessage
(); oMail.IsBodyHtml = true;
oMail.Body = "your message body goes here";
oMail.Subject = "your subject goes here";
smtpClnt.Timeout = 100000;
smtpClnt.EnableSsl = true;
System.Net.NetworkCredential nc
= new System.Net.NetworkCredential("[email protected]",
"your_password"); smtpClnt.Credentials = nc;
Attachment oAttached
= new Attachment
("C:\\yourimage.jpg"); oMail.Attachments.Add(oAttached);
smtpClnt
.SendCompleted += new SendCompletedEventHandler
(MailDeliveryComplete
);
smtpClnt.SendAsync(oMail, "sending");
}
catch (Exception mailExc) {
if (mailExc.ToString().IndexOf("could not be resolved") >= 0) {
int line = mailExc.ToString().IndexOf("line");
int leng = mailExc.ToString().Length;
string sLin = mailExc.ToString().Substring(line, (leng - line));
string s = "Either the developer's Gmail SMTP was unavailable, or else your computer is not currently ";
s += "connected to the internet. Error generated at source code " + sLin;
MessageBox.Show(s, "Unable to send character file via email");
}
else {
MessageBox.Show("Error:" + Environment.NewLine + Environment.NewLine +
mailExc.Message + Environment.NewLine + Environment.NewLine + mailExc.ToString());
}
}
finally {
//don't invoke smtpClnt.Dispose() here; if you do, the mail never sends
}
}
}
private void MailDeliveryComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e) {
string myMessage = e.ToString();
string myCaption = string.Empty;
if (e.Error != null) {
myCaption = "Error sending email";
}
else if (e.Cancelled) {
myCaption = "Sending of email cancelled.";
}
else {
myCaption = "Your email message was sent successfully to the Game Master.";
}
MessageBox.Show(myMessage, myCaption);
}