C# code send attachment(.csv file) in email where the attachement is done as an in-memory operation

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 445
The below code will do so

public static void SendEmailWithAttachment(StringBuilder sb, Tuple<string, int, string, string> smptTuple, Tuple<string, string, string, string, string, string> emailInfoTuple)
{
try
{
string smptHost = smptTuple.Item1;
int smptPort = smptTuple.Item2;
string smptUser = smptTuple.Item3;
string smptPassword = smptTuple.Item4;
string fromEmailAddress = emailInfoTuple.Item1;
string toEmailAddress = emailInfoTuple.Item2;
string ccEmailAddress = emailInfoTuple.Item3;
string subject = emailInfoTuple.Item4;
string body = emailInfoTuple.Item5;
string attachmentName = emailInfoTuple.Item6;

using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(sb.ToString())))
{
MailMessage mailMsg = new MailMessage();
MailAddress emailAddress = new MailAddress(toEmailAddress);
mailMsg.To.Add(emailAddress);

foreach (var address in ccEmailAddress.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries))
{
mailMsg.CC.Add(address);
}

mailMsg.From = new MailAddress(fromEmailAddress);

//Add a new attachment to the E-mail message, using the correct MIME type
Attachment attachment = new Attachment(stream, new ContentType("text/csv"));
attachment.Name = attachmentName;
mailMsg.Attachments.Add(attachment);

mailMsg.Subject = subject;
mailMsg.Body = body;
mailMsg.IsBodyHtml = true;

// Init SmtpClient
SmtpClient smtpClient = new SmtpClient(smptHost, smptPort);
smtpClient.EnableSsl = false;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smptUser, smptPassword);
smtpClient.Credentials = credentials;

//send email
smtpClient.Send(mailMsg);
}
}
catch (Exception ex)
{
throw ex;
}
}

Comments or Responses

Login to post response