Friday, 30 May 2014

Send mail with Attachment File

public static string SendMailWithFile(string ToEmail, string subject, string body, string attachmentFilename)
    {
        try
        {
            string MailSenderEmail = ConfigurationManager.AppSettings["SenderEmail"].ToString();
            string MailSenderPwd = ConfigurationManager.AppSettings["SenderPwd"].ToString();
            string smtpInfo = ConfigurationManager.AppSettings["smtpInfo"].ToString();
            SmtpClient smtpClient = new SmtpClient();
            NetworkCredential basicCredential = new NetworkCredential(MailSenderEmail, MailSenderPwd);
            MailMessage message = new MailMessage();
            MailAddress fromAddress = new MailAddress(MailSenderEmail);

            // setup up the host, increase the timeout to 5 minutes
            smtpClient.Host = smtpInfo;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = basicCredential;
            smtpClient.Timeout = (60 * 5 * 1000);
            message.From = fromAddress;
            message.Subject = subject;
            message.IsBodyHtml = true;
            message.Body = body;
            message.To.Add(ToEmail);
            message.Bcc.Add("dharmendrap2@gmail.com");
            if (!string.IsNullOrEmpty(attachmentFilename))
            {
                Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
                ContentDisposition disposition = attachment.ContentDisposition;
                disposition.CreationDate = File.GetCreationTime(attachmentFilename);
                disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
                disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
                disposition.FileName = Path.GetFileName(attachmentFilename);
                disposition.Size = new FileInfo(attachmentFilename).Length;
                disposition.DispositionType = DispositionTypeNames.Attachment;
                message.Attachments.Add(attachment);
            }
            smtpClient.Port = 587;
            smtpClient.EnableSsl = true;
            smtpClient.Send(message);
            return "1";
        }
        catch (Exception ex)
        {          
            throw ex;
        }
    }

No comments:

Post a Comment