Sep
06
2006
Send mail with username and password against other email server
Posted by admin under
ASP.NET articles
This little snippet is what I use when I send emails from my ASP.NET applications. While the default SMTP server is closed on my box I need to authenticate against the mail server and the code for that is nothing you remember from time to time - so here it is:
public static void SendMail(string sHost, int nPort, string sUserName, string sPassword, string sFromName, string sFromEmail,
string sToName, string sToEmail, string sHeader, string sMessage )
{
if ( sToName.Length == 0 )
sToName = sToEmail;
if ( sFromName.Length == 0 )
sFromName = sFromEmail;
System.Web.Mail.MailMessage Mail = new System.Web.Mail.MailMessage();
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = sHost;
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = nPort.ToString();
if( sUserName.Length == 0 )
{
//Ingen auth
}
else
{
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = sUserName;
Mail.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = sPassword;
}
Mail.To = sToEmail;
Mail.From = sFromEmail;
Mail.Subject = sHeader;
Mail.Body = sMessage;
Mail.BodyFormat = System.Web.Mail.MailFormat.Html;
System.Web.Mail.SmtpMail.SmtpServer = sHost;
System.Web.Mail.SmtpMail.Send(Mail);
}
So calling it is like:
SendMail("mail.yourdomain.com", 25,
"useraccount@yourdomain.com",
"yourmailpassword", "Your name", "yourmail@yourdomain.com",
"Donald Duck", "donald@domain.com", "Hello there", "How are you?<br>I am fine!");
Actually this is a modified version of my own function, I use web.config for host/port etc so that doesn't have so be sent in every time, but I tried to keep this example to clean as possible. Also some error checking might be good for you to add, if using it for real.