Sending email with attachments from C#


In many cases you may required to send emails using ASP.NET. You can have all the classes required to send an email in the System.Net.Mail namespace. You can send an email from ASP.NET as follows :

First you have to add these namespaces to your code behind file:

1. using System.Net;
2. using System.Net.Mail;

Then write the following method

public void email_send()
{
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    mail.From = new MailAddress("your mail@gmail.com");
    mail.To.Add("to_mail@gmail.com");
    mail.Subject = "Test Mail - 1";
    mail.Body = "mail with attachment";

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
    mail.Attachments.Add(attachment);

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("your mail@gmail.com", "your password");
    SmtpServer.EnableSsl = true;

    SmtpServer.Send(mail);

}

Using the above you can send attachemebts also. Hope this helps :-)

7 comments:

  1. This is really helpful for me, thank you very much

    ReplyDelete
  2. Hi, thank you for sharing the codes.

    I am trying your code but I got this error "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at"

    that error happens at --> SmtpServer.Send(mail);

    Do you know how to solve this? Thank you

    ReplyDelete
    Replies
    1. Hi, Can you please check this link once. It explained the same issue.

      http://stackoverflow.com/questions/20906077/gmail-error-the-smtp-server-requires-a-secure-connection-or-the-client-was-not

      Delete
  3. This will guarantee that the messages that you send contain data that they are occupied with. It likewise decreases the shot of individuals unsubscribing because of getting an excessive number of messages that they are not intrigued by. TalkTalk mail

    ReplyDelete