Hi guys, long time no see. Been busy with lots of projects recently.
OK let share this sample code to send mail HTML page using gmail server in C#:
private String readHtmlPage(string url)
{
if (!System.IO.File.Exists(url)) return string.Empty;
try
{
String result;
WebResponse objResponse;
WebRequest objRequest = System.Net.HttpWebRequest.Create(url);
objResponse = objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}
catch (Exception ex)
{
App.LogError(ex);
return string.Empty;
}
}
private void SendMailBtn_Click(object sender, EventArgs e)
{
string mail = readHtmlPage(url);
if (mail.Trim().Length == 0) return;
string toAddress = "
to_one@yahoo.co.uk";
string fromAddress = "
someone@gmail.com";
try
{
if (fromAddress.Trim().Length == 0)
{
MessageBox.Show(this, "Cannot send mail from an empty address. Please confirm the setting email.", "Byaxiom SendMail", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (toAddress.Trim().Length == 0)
{
MessageBox.Show(this, "Cannot send mail to an empty address. Please confirm the customer email.", "Byaxiom SendMail", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true;
msg.From = new MailAddress(fromAddress);
msg.To.Add(toAddress);
if (AppSettings.Default.EMailCopy.Length > 0)
msg.CC.Add("
mycopyemail@yahoo.com");
msg.Subject = subject;
msg.Body = message;
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
mailClient.EnableSsl = true;
NetworkCredential cred = new NetworkCredential(toAddress, "fromAddresspassword");
mailClient.Credentials = cred;
mailClient.Send(msg);
MessageBox.Show(this, "Track report mail sent to " + toAddress + ". Please confirm by checking your mail copy", "Byaxiom SendMail", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
App.LogError(ex);
MessageBox.Show(this, "There was an error sending mail. Please check your setings and internet connection.", "Byaxiom SendMail", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}