Wednesday, June 16, 2010

Sending email through a Google Apps account With ASP.NET

//Include Namespace

using System.Net.Mail;
using System.Net;
using System.IO;




//Code for sending mail

string mailFrom = "email id which appears in receiver's inbox";
string mailToInquiry = "receiver's email id";
string mailServer = "smtp.gmail.com";
string mailUsername = "email id which you want to use for sending email";
string mailPassword = "password of above email id";
int mailPort = 587;


string msgBody = "";
if (File.Exists(MapPath("emailInquiry.htm")))
{
String fileName = Server.MapPath("emailInquiry.htm"); ;
StreamReader strmR = File.OpenText(fileName);
msgBody = strmR.ReadToEnd();
strmR.Close();
}

msgBody = msgBody.Replace("{VAR_Name}", txtName.Text);
msgBody = msgBody.Replace("{VAR_Address}", txtAddress.Text);
msgBody = msgBody.Replace("{VAR_ContactNo}", txtContactNo.Text);
msgBody = msgBody.Replace("{VAR_Email}", txtEmail.Text);
msgBody = msgBody.Replace("{VAR_Comments}", txtComments.Text);

// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.

// Create a message and set up the recipients.
MailMessage message = new MailMessage(
mailFrom,
mailToInquiry,
txtName.Text + " is wants to contact you.",
msgBody);

message.IsBodyHtml = true;

//Send the message.
SmtpClient client = new SmtpClient(mailServer);
// Add credentials if the SMTP server requires them.

client.Port = mailPort;
client.EnableSsl = true;
client.Timeout = 60000;
client.Credentials = new NetworkCredential(mailUsername, mailPassword);
// smtp.Send(mail);


try
{
client.Send(message);
ClearData();

LblMsg.Text = "Thank you for contacting us we will get back to you as soon as possible..!!";
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
ex.ToString());
}