Step 1: Declare the System.Net.Mail namespace
using System.Net.Mail;
Step 2: Create a MailMessage object. This class contains the actual message you want to send. There are four overloaded constructors provided in this class. We will be using
public MailMessage ( string from, string to, string subject, string body );
The constructor of this MailMessage class is used to specify the sender email, receiver email, subject, body.
MailMessage message = new MailMessage ("abc@somedomain.com","administrator@anotherdomain.com","Testing","This is a test mail");
Step 3: To add an attachment to the message, use the Attachment class.
string fileAttach = Server.MapPath("myEmails") + "\\Mypic.jpg"; Attachment attach = new Attachment(fileAttach); message.Attachments.Add(attach);
Step 4:After creating a message, use the SmtpClient to send the email to the specified SMTP server. I will be using ‘localhost’ as the SMTP server.
SmtpClient client = new SmtpClient("localhost"); client.Send(message); Additionally, if required, you client.Timeout = 500; // Pass the credentials if the server requires the client to authenticate before it will send e-mail on the client's behalf. client.Credentials = CredentialCache.DefaultNetworkCredentials;
That’s it. It’s that simple.
To configure SMTP configuration data for ASP.NET, you would add the following tags to your web.config file.
<system.net>
<mailSettings>
<smtpfrom="abc@somedomain.com">
<networkhost="somesmtpserver"port="25"userName="name"password="pass"defaultCredentials="true" />
</smtp>
</mailSettings>
</system.net>
References :
http://msdn2.microsoft.com/En-US/library/system.net.mail.mailmessage.aspx
No comments:
Post a Comment