Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Send Email With Attachment In Asp.Net

Tags:

c#

asp.net

smtp

I need to attach an image with my email in asp.net the file is already added in the solution explorer but I dont know how to add this with my email please guide me

My current code is given below

public void SendMail()
{
    try
    {
        string receiverEmailId = "[email protected]";
        string senderName = ConfigurationManager.AppSettings["From"].ToString();
        string mailServer = ConfigurationManager.AppSettings["SMTPServer"].ToString(); ;
        string senderEmailId = ConfigurationManager.AppSettings["SMTPUserName"].ToString();
        string password = ConfigurationManager.AppSettings["SMTPPasssword"].ToString();
        var fromAddress = new MailAddress(senderEmailId, senderName);
        var toAddress = new MailAddress(receiverEmailId, "Alen");
        string subject = "subject";
        string body = "body.";
        var smtp = new SmtpClient
        {
            Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new NetworkCredential(fromAddress.Address, password)
        };
        using (var message = new MailMessage(fromAddress, toAddress)
        {
            Subject = subject,
            Body = body
        })
        {
            smtp.Send(message);
        }
    }
    catch (Exception ex)
    {
    }
}
like image 470
Optimus Avatar asked Feb 22 '13 04:02

Optimus


People also ask

Which namespace using can send email in ASP NET MVC?

For sending mail from ASP.NET MVC we use the "System. Net.Mail" namespace.


1 Answers

Did you check out MailMessage.Attachments property (see MSDN)?

// create attachment and set media Type
//      see http://msdn.microsoft.com/de-de/library/system.net.mime.mediatypenames.application.aspx
Attachment data = new Attachment(
                         "PATH_TO_YOUR_FILE", 
                         MediaTypeNames.Application.Octet);
// your path may look like Server.MapPath("~/file.ABC")
message.Attachments.Add(data);
like image 55
Pilgerstorfer Franz Avatar answered Oct 15 '22 13:10

Pilgerstorfer Franz