Tuesday, November 11, 2008

How to send mail using Smtp Object?

SMTP :- Simple Mail Transfer Protocol
In ASP.NET applications we use Smtp Client object to send mails.
Before sending mail , we should prepare the mail message and for which there is a class called Mail Message.
So object created to Mail Message class is used to define subject, body, Mail From , Mail To , Content type is HTML or not, etc…
Also for this Smpt Client Object we should assign attributes like Mail server IP , Port number etc.. to send mails from application.
These mail server details can either be configured in web.config file or shall be hard coded in code or can be saved in a data base table.
In Web.config

<system.net>
<mailSettings>
<smtp from="Admin@app.com" deliveryMethod="Network">
<network host="Your Mail Server IP" port="Mail server port (Default 25)"/>
</smtp>
</mailSettings>
</system.net>


Through code


string strFromEmailID="Hello@app.com";
string argEmailId ="Hello1@app.com";

SmtpClient smtpMail = new SmtpClient();
smtpMail.Host = strMailServerIP;
smtpMail.Port = 25;

MailMessage mailMsg = new MailMessage();
mailMsg.Subject ="Hello";
mailMsg.Body = ="Hello ";
mailMsg.To.Add(argEmailId);
mailMsg.From = new MailAddress(strFromEmailID);
mailMsg.IsBodyHtml = true;
smtpMail.Send(mailMsg);

No comments: