Send email in asp.net with attachmentIntroduction
Most of the systems need a feature to send email to users. For example, when a user registers to a website a user activation mail is sent to the user email id. Or some sites send email to the make the users know about the new product that they have launched. Sometimes this mail contains some attachment. Here we will discuss how to send an email with an attachment.
Sending emails very easily with ASP.Net. For this, we need to add System.NET.Mail namespace that contains all the required classes to send an email.
Let us look at the implementation of these features with ASP.NET 3.5.
Implementation
First, we need to add two namespaces.
using System.Net;
using System.Net.Mail;
Then write a method "SendEmailWithAttamentWithSyncMode" to send email.
private void SendEmailWithAttamentWithSyncMode(string[] fileNames)
{
try
{
MailMessage message = new MailMessage();
//from address
message.From = new MailAddress("fromEmailAddress", "FromDisplayName");
// to address
message.To.Add(new MailAddress("ToEmailAddress", "ToDisplayName"));
// set content email
message.Body = "This is auto generated email dont reply and you have two attachements also";
//set this email content display user inbox like Html format
message.IsBodyHtml = true; // this is the heading of the email
message.Subject = "The dotnetlogiX.com Message";
//attach our file to mail message as attachment
//here we can add more than one attachments
foreach (string filePaths in fileNames)
{
message.Attachments.Add(new Attachment(filePaths));
}
// 25 is default for SMTP server
SmtpClient emailClient = new SmtpClient("ServerIP", 25);
emailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
// set users to default use the default credential
emailClient.UseDefaultCredentials = true;
emailClient.Send(message);
}
catch (SmtpException smtpex)
{
throw smtpex;
}
catch (Exception ex)
{
throw ex;
}
}
In the above method, we have created a mail message object and then set from email, to email address. then the body for the message and contents too. Then we have set this email to display in user inbox like HTML format.
Then we add our attachment to the email message and finally passed to the Smtpclient object with the send method.
Now using this method you can send your mail.