注意:微软465端口被占用发送不能邮件,请使用25或者587
class MailService
{
private string mailHost = "";
private string mailFromName = "";
private string mailUsername = "";
private string mailPassword = "";
private bool mailSMTPSecure = true;
private int mailPort = 25;
public bool sendHtml(string to, String cc, string bcc, string subject, string body, string[] attachments, string from)
{
try
{
SmtpClient SmtpClient = new SmtpClient();
SmtpClient.Host = mailHost;
SmtpClient.Port = mailPort;
SmtpClient.UseDefaultCredentials = false;
SmtpClient.EnableSsl = mailSMTPSecure;
SmtpClient.Credentials = new NetworkCredential(mailUsername, mailPassword);
SmtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpClient.Send(getSendEmailArray(to,cc,bcc, subject, body, attachments, from));
return true;
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return false;
}
private MailMessage getSendEmailArray(string to, String cc, string bcc, string subject, string body, string[] attachments, string from)
{
string[] fromArr = new string[] { mailUsername, mailFromName };
if (from == mailUsername)
{
fromArr = new string[] { mailUsername, mailFromName };
}
MailMessage mailMessage = new MailMessage();
if (!string.IsNullOrEmpty(to))
{
string[] toEmails = to.Split(';');
foreach (string toEmail in toEmails)
{
if (string.IsNullOrEmpty(toEmail))
{
continue;
}
mailMessage.To.Add(toEmail);
}
}
if (!string.IsNullOrEmpty(cc))
{
string[] ccEmails = cc.Split(';');
foreach (string ccEmail in ccEmails)
{
if (string.IsNullOrEmpty(ccEmail))
{
continue;
}
mailMessage.CC.Add(ccEmail);
}
}
if (!string.IsNullOrEmpty(bcc))
{
string[] bccEmails = bcc.Split(';');
foreach (string bccEmail in bccEmails)
{
if (string.IsNullOrEmpty(bccEmail))
{
continue;
}
mailMessage.Bcc.Add(bccEmail);
}
}
foreach (string attachmentd in attachments)
{
if (!File.Exists(@attachmentd))
{
continue;
}
mailMessage.Attachments.Add(new Attachment(attachmentd));
}
mailMessage.From = new MailAddress(fromArr[0], fromArr[1]);
mailMessage.Subject = subject;
mailMessage.Body = body;
return mailMessage;
}
}