Wednesday, April 11, 2007

ASP.NET 2.0 - Sending Email with your application

This is a very simplistic example of how to send an email within your ASP.NET 2.0 application. This example uses Google's gmail service, although it should work with any SMTP email server as long as you have the correct server settings (Host, Port, SSL) Good luck with your application!


public bool SendEmail(string strTo, string strSubject, string strBody)
{
bool bReturn=false;

System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();

mail.From = new MailAddress("sender@gmail.com", "Senders Name");
mail.ReplyTo = new MailAddress("sender@gmail.com"); // optional
mail.To.Add(strTo);
mail.Subject = strSubject;
mail.Body = strBody;
mail.IsBodyHtml = true;

smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("sender@gmail.com", "password");
smtp.Send(mail);

bReturn = true;
return bReturn;
}

1 comment:

g michael amante said...

telnet new.toad.com 25

HELO mydomain.com
MAIL FROM: sender@mydomain.com
RCPT TO: friend@example.com
DATA
Subject: test message
From: sender@mydomain.com
To: friend@example.com

You though that was geeky,
This is an example of what this code is actually doing. Making a telnet connection to the remote host on port 25 of an SMTP server, communicating to the server using the commands issued above.
You can try for yourself if you don't believe me. My friend Chris taught me about this, and it's the reason why email SPAM became such a problem.
.