C#发送邮件,主要使用的是System.Net.Mail命名空间下的方法实现,方法很简单,短短十几行代码即可完成发送,具体代码如下。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace SendMessage
{
public class SendEmail:ISend
{
public SendResult Send(string[] addresses, string title, string content)
{
SendResult result = new SendResult();
if (addresses.Length == 0)
{
result.returnstr = "目标地址为空";
}
else if (string.IsNullOrEmpty(content)) {
result.returnstr = "内容为空";
}
else if (string.IsNullOrEmpty(title)) {
result.returnstr = "标题为空";
}
else
{
try
{
MailMessage myMail = new MailMessage();
myMail.From = new MailAddress("xxxx@xxxx.cn");
foreach (var address in addresses)
{
myMail.To.Add(new MailAddress(address));
}
myMail.Subject = title;
myMail.SubjectEncoding = Encoding.UTF8;
myMail.Body = content;
myMail.BodyEncoding = Encoding.UTF8;
myMail.IsBodyHtml = false;
myMail.Priority = MailPriority.High;
//myMail.CC
//myMail.Bcc
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "xxxx.xxxx.com";
//smtpClient.Port = 23;
smtpClient.Credentials = new NetworkCredential("xxxx@xxxx.cn", "yourpassword");
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
//smtpClient.EnableSsl = true;
smtpClient.Send(myMail);
result.status = true;
}
catch (Exception ex)
{
result.returnstr = ex.Message;
}
}
return result;
}
}
}
这样邮件就可以发送了。目前主流的一些邮件服务提供商都支持这样发送,但也碰到部分邮箱无法发送,如最近发现新浪的.cn邮箱没法用这种方式发送邮件了,之前是可以的,具体原因也还没空细究。
如果是用自己公司的邮箱一般都没啥问题,亲们可以试试。
源码下载地址:SendEmail.rar