Tuesday, December 1, 2009

Send Smtp Email with Attachment

public void SendSmtpClientMail()

{

byte[] FileBytes=..;

string ContentType=..;

string FileName=..;

MailMessage objMailMessage = new MailMessage("mailFrom@domain.com","mailTo@domain.com","Subject message","Body Message");

//file attachment, if need multiple attach do loop for .Attachments.Add(objAttachment);

MemoryStream objMemoryStream = new MemoryStream(FileBytes);

//Create the file attachment for this e-mail message

Attachment objAttachment = new Attachment objMemoryStream,ContentType);

objAttachment.ContentDisposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;

objAttachment.ContentDisposition.FileName =FileName;
//Add the file attachment to this e-mail message.
objMailMessage.Attachments.Add(objAttachment);

string hostName = System.Configuration.ConfigurationManager.AppSettings["HostName"].ToString();

string userName = System.Configuration.ConfigurationManager.AppSettings["MailUserName"].ToString();
string password = System.Configuration.ConfigurationManager.AppSettings["MailPassword"].ToString();

if (hostName == null hostName.Length == 0) throw new
Exception
("Mail Server Host Name is missing or empty in Web.Config. Please contact administrator");
else if (userName == null userName.Length == 0) throw
new Exception("Mail Server User Name is missing or empty in Web.Config. Please contact administrator");

SmtpClient smtpMail = new SmtpClient(hostName);
smtpMail.Credentials = new NetworkCredential(userName, password);
try
{
smtpMail.Send(objMailMessage);
}
catch (SmtpFailedRecipientException ex)
{
throw new Exception("Error occurred while sending an email.
Possible causes include invalid email address"
);

}
catch (Exception ex)
{
throw new
Exception
("Error occurred while sending an email.
Possible causes include invalid mail server credentials"
);

}
}

No comments:

Post a Comment