Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to send an e-mail with attachment and delete the attachment afterwards in C#

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 866
    Comment on it

    Sending an e-mail with an attachment through a .net application include these simple steps:-

    1)- Use the following namespaces -
    using System.Net;
    using System.Net.Mail;
    using System.IO;

    2)- Call the following function where you have to send an email.

    public void SendMail()
    {
    MailMessage msg = new MailMessage();
    // Enter your mail id from which you have to send an email
    msg.From = new MailAddress("sender email id");
    // Enter your mail id to which you have to send an email
    msg.To.Add("reciever email id");
    msg.Body = "";
    msg.IsBodyHtml = true;
    msg.BodyEncoding = System.Text.Encoding.GetEncoding("utf-8");
    Attachment at = new Attachment("Enter path of the file to attach");
    msg.Attachments.Add(at);
    msg.Subject = "Enter Message subject here ";
    SmtpClient mailClient = new SmtpClient();
    // Enter the smtp client here for example smtp client for gmail is smtp.gmail.com
    mailClient.Host = "SMTP CLIENT";
    msg.Body = "Enter Message Body here";
    mailClient.Credentials = new System.Net.NetworkCredential("Sender Email ID", "Password");
    mailClient.Send(msg);
    mailClient.Dispose();
    at.Dispose();
    msg.Dispose();
    }

    Deleting the attachment after its sent away:-

    3)- Call the following function to delete the attachment

    protected void DeleteFile()
    {
    if (File.Exists("Enter path of the file")
    {
    File.Delete("Enter path of the file");
    }
    }

    Please note that the attached file will not gets deleted unless all the resources used in sending mail have been released i.e calling of dispose method is mandatory as I have done in last 3 steps of the SendMail() function.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: