Sending mails from .net code is very easy. System.Net.Mail namespace provides classes that support mail.
At a high level, there are only two things we need to do.
- Construct a MailMessage object.
- Use a SMTPClient object to send the MailMessage object constructed in the previous step.
Following are the steps to send a simple mail.
Step 1: Create a MailMessage object
Create a MailMessage object.
MailMessage message = new MailMessage();
Step 2: Specify the from and to addresses
From and To addresses can be specified in the constructor itself. If not done in constructor, it can be done at a later point using the MailMessage.From and MailMessage.To properties.
Step 3: Specify Subject
Subject can also be specified through the constructor. If not done in constructor, assign a subject string to MailMessage.Subject property.
Step 4: Create the body/content
The body of the mail should be a string. This could be a plain text or an HTML. By default the plain text is assumed to be the type of the body content.
If you create the body using html, set MailMessage.IsBodyHtml property to true.
Step 5: Create SmtpClient object and use the Send method
Create the mail client and specify the SMTP host for it. Set the SmtpClient.UseDefaultCredentials to true.
Then use the SmtpClient.Send() method to send the MailMessage object we built in the previous steps.
Code snippet to send a sample mail
private static void Main(string[] args)
{
MailMessage message = new MailMessage(@"saravanandss@gmail.com",
@"saravanandss@gmail.com");
message.Subject = "Check SMTP Mail";
message.Body = @"<html><body><h4>Sample mail body.</h4></body></html>";
message.IsBodyHtml = true;
using (SmtpClient mailClient = new SmtpClient())
{
mailClient.Host = @"smtp.mysite.com";
mailClient.UseDefaultCredentials = true;
mailClient.Send(message);
}
}
Like this:
Like Loading...
Related
Pingback: Anonymous
Pingback: Rare Coin Buyer
The remote certificate is invalid according to the validation procedure. gives this error
Sir, I want to send an email using ASP.net. I would like to send the e-mail from any e-mail account. not particulary the Gmail account. So when I am entering the yahoo email account in the from address, the application is not working. Can you please suggest your ideas. Thanks
Hi vasu,
The from address should get authenticated by the host server (The server name you provide in the Host property of SmtpClient).
I am not sure about your purpose, but if you want to send a mail from your yahoo address, consider changing the host server to Yahoo’s specific SMTP server.