MailMessage
suggest changeThis example creates a mail message with attachments and sends it with SmtpClient. The code sets the SMTP port to 25, which is the protocol default. Any requires using System.Linq.
public class clsMail
{
private static bool SendMail(string mailfrom, List<string>replytos, List<string> mailtos, List<string> mailccs, List<string> mailbccs, string body, string subject, List<string> Attachment)
{
try
{
using(MailMessage MyMail = new MailMessage())
{
MyMail.From = new MailAddress(mailfrom);
foreach (string mailto in mailtos)
MyMail.To.Add(mailto);
if (replytos != null && replytos.Any())
{
foreach (string replyto in replytos)
MyMail.ReplyToList.Add(replyto);
}
if (mailccs != null && mailccs.Any())
{
foreach (string mailcc in mailccs)
MyMail.CC.Add(mailcc);
}
if (mailbccs != null && mailbccs.Any())
{
foreach (string mailbcc in mailbccs)
MyMail.Bcc.Add(mailbcc);
}
MyMail.Subject = subject;
MyMail.IsBodyHtml = true;
MyMail.Body = body;
MyMail.Priority = MailPriority.Normal;
if (Attachment != null && Attachment.Any())
{
System.Net.Mail.Attachment attachment;
foreach (var item in Attachment)
{
attachment = new System.Net.Mail.Attachment(item);
MyMail.Attachments.Add(attachment);
}
}
using (SmtpClient smtpMailObj = new SmtpClient())
{
smtpMailObj.Host = "your host";
smtpMailObj.Port = 25;
smtpMailObj.Credentials = new System.Net.NetworkCredential("uid", "pwd");
smtpMailObj.Send(MyMail);
}
return true;
}
}
catch
{
return false;
}
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents