Monday, March 6, 2017

C# - code to send email from SMTP with an attachments

 

string smtpServer = “SMTP Server”;
string fromAddress = “SMTP From Address”;
mailMessage.From = new MailAddress(“SMTP Email Address”);
mailMessage.Bcc.Add(toAddress);Dictionary<byte[], string> fileCollection = svc.getAttchmentDetails(MessageID);
mailMessage.Subject = emailSubject;
mailMessage.IsBodyHtml = IsBodyHtml;

// get the file from SQL DB

Dictionary<byte[], string> fileCollection = svc.getAttchmentDetails(MessageID);

   if (IsBodyHtml)
    emailBody = Regex.Replace(emailBody, @"(<img\/?[^>]+>)", @"", RegexOptions.IgnoreCase);

   foreach (KeyValuePair<byte[], string> entry in fileCollection)
          {
          string fileName = entry.Value.ToString();
          byte[] objContext = (byte[])entry.Key;
          MemoryStream memoryStreamOfFile = new MemoryStream(objContext);
         mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, fileName, MimeMapping.GetMimeMapping(fileName)));
          }
mailMessage.Body = emailBody;
if(msgPriority.Contains("True"))
mailMessage.Priority = MailPriority.High;
smtpClient = new SmtpClient(smtpServer);
smtpClient.Send(mailMessage);
file.WriteLine("Email Send Out Successfully");
msgStatus[0] = "Success";

No comments:

Post a Comment