您的位置:首页 > 大数据 > 人工智能

C#发送邮件(使用Gmail或自己配置的SMTP)

2012-01-13 17:32 866 查看
发送邮件需要SMTP服务器,可以使用Gmail的SMTP服务器,也可以使用IIS自带的SMTP服务,还可以使用第三方的SMTP服务器

如果使用Gmail,需要用Gmail的用户名密码作为认证信息,没有办法自定义发件人地址,总会显示为Gmail邮箱地址。并且必须使用SSL发送。

如果使用IIS自带的SMTP服务,需要在IIS里配置SMTP服务器,如图所示



选中“使用Localhost”即可。但是如果使用Window7或Vista,操作系统已经将SMTP组件去掉了,即使IIS里配置了Localhost也不会起作用。

这时我们可以使用第三种方法,使用第三方的SMTP服务器,推荐Free SMTP Server,这是个免费的,好用的服务器,安装后双击运行起来就可以了。之后我们在程序里将SMTP服务器地址配置为localhost即可。下面是邮件发送代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;

namespace WheatStudio.Utility.Mail
{

public static class MailUtility
{
public class SmtpContext
{
public string Server { get; set; }
public int Port { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public bool EnableSSL { get; set; }
}
private static Encoding myEncoding;
public static Encoding MyEncoding
{
get
{
if (myEncoding == null)
{
myEncoding = Encoding.UTF8;
}
return myEncoding;
}
set
{
myEncoding = value;
}
}
public static void SendMail(SmtpContext smtp, List<string> toAddressList, string fromAddress, string fromDisplayName, string title, string htmlBody)
{
System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
foreach (string address in toAddressList)
{
msg.To.Add(address);
}
msg.From = new MailAddress(fromAddress, fromDisplayName, MyEncoding);//发件人地址,发件人姓名,编码
msg.Subject = title;    //邮件标题
msg.SubjectEncoding = MyEncoding;
msg.Body = htmlBody;    //邮件内容
msg.BodyEncoding = MyEncoding;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.Normal;

SmtpClient client = new SmtpClient();
client.Host = smtp.Server;
if (smtp.Port != 0)
{
client.Port = smtp.Port;//如果不指定端口,默认端口为25
}
if (!string.IsNullOrEmpty(smtp.UserName))
{
client.Credentials = new System.Net.NetworkCredential(smtp.UserName, smtp.Password);//向SMTP服务器提交认证信息
}
client.EnableSsl = smtp.EnableSSL;//默认为false
client.Send(msg);
}
}
}


下面是调用代码

MailUtility.SmtpContext gmailSmtp = new MailUtility.SmtpContext()
{
Server = "smtp.gmail.com",
UserName = "*****@gmail.com",
Password = "********",
EnableSSL = true    //发送邮件 (SMTP) 服务器 - 需要 TLS2 或 SSL
};
MailUtility.SmtpContext mySmtp = new MailUtility.SmtpContext()
{
Server = "localhost"
};
//使用Gmail的SMTP服务器发送邮件,需要Gmail用户名密码作为认证信息,发件人地址会被强制转换为Gmail邮箱,必须使用SSL发送
MailUtility.SendMail(gmailSmtp, new List<string> { "***@mapuni.com" }, "***@dreamarval.com", "发件人显示名", "测试邮件,使用Gmail发送", "<h4>Hellow mail!!<br /><a href='http://www.google.com.hk'>google</a></h4>");
//使用自己配置的SMTP服务器,可以任意指定发件人地址
MailUtility.SendMail(mySmtp, new List<string> { "***@mapuni.com" }, "***@dreamarval.com", "发件人显示名", "测试邮件,使用自己配置的SMTP服务器发送", "<h4>Hellow mail!!<br /><a href='http://www.google.com.hk'>google</a></h4>");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: