Email sending script from C#

Sending an email from C# script is quite easy thing. Most popular two ways to send an email from C# scripts are as follows:
1.)
public string sendingMail(string strFrom, string strTo, string strSubject, string strMessage)
{
MailMessage myMessage = new MailMessage(new MailAddress(strFrom), new MailAddress(strTo));
myMessage.IsBodyHtml = true;
myMessage.Priority = MailPriority.Normal;
myMessage.Body = strMessage;
myMessage.Subject = strSubject;
SmtpClient client = new SmtpClient(“”, 25);
try
{
client.Send(myMessage);
}
catch(Exception ex)
{
return ex.ToString();
}
return “Message Has Been Sent”;
}

2.)
public string AuthenticatedMailSend(string mailTo, string Subject, string MessageBody)
{
System.Net.Mail.MailMessage email = new MailMessage(“TEST@test.com”, mailTo);
email.Subject = Subject;
email.IsBodyHtml = true;
email.Body = MessageBody;

System.Net.Mail.SmtpClient mailClient = new SmtpClient();
System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential(“”, “”);
mailClient.Host = “”;
mailClient.Port = 25;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicAuthenticationInfo;

try
{
mailClient.Send(email);
}
catch (Exception ex)
{
return ex.ToString();
}

return “1”;
}

You ccan use any of the above methods, some mail server only supports authenticated email send by script. In that case, go for 2nd method.

Don’t forget to reference “using System.Net.Mail;” namespace for sending an email.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: