You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
3.3 KiB

4 years ago
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace CK.SCP.Common
{
public class MyWebSmtpMail
{
private MailMessage mailMessage;
private SmtpClient smtpClient;
private string from;
private string server;
private string username;
private string password;
private bool enablessl;
private bool credentials;
private int port;
public MyWebSmtpMail()
{
string From = ConfigurationManager.AppSettings["MailSender"];
string Server = ConfigurationManager.AppSettings["MailServer"];
string UserName = ConfigurationManager.AppSettings["MailUserName"];
string Password = ConfigurationManager.AppSettings["MailPassword"];
int Port = Convert.ToInt32(ConfigurationManager.AppSettings["MailPort"]);
this.from = From;
this.server = Server;
this.password = Password;
this.username = UserName;
this.enablessl = false;
this.port = Port;
this.credentials = false;
}
public void Send(string To, string Body, string Title)
{
mailMessage = new MailMessage();
mailMessage.To.Add(To);
mailMessage.From = new System.Net.Mail.MailAddress(this.from);
mailMessage.Subject = Title;
mailMessage.Body = Body;
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
mailMessage.Priority = System.Net.Mail.MailPriority.Normal;
if (mailMessage != null)
{
smtpClient = new SmtpClient();
if (!credentials)
{
smtpClient.Credentials = new System.Net.NetworkCredential(username, password);
}
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Host = server;
smtpClient.Port = port;
smtpClient.EnableSsl = enablessl;
//smtpClient.Send(mailMessage);
//smtpClient.SendAsync(mailMessage, null);
//如果服务器支持安全连接,则将安全连接设为true
//smtpClient.EnableSsl = true;
try
{
//是否使用默认凭据,若为false,则使用自定义的证书,就是下面的networkCredential实例对象
smtpClient.UseDefaultCredentials = false;
//指定邮箱账号和密码,需要注意的是,这个密码是你在QQ邮箱设置里开启服务的时候给你的那个授权码
System.Net.NetworkCredential networkCredential = new System.Net.NetworkCredential(username, password);
smtpClient.Credentials = networkCredential;
//发送邮件
smtpClient.Send(mailMessage);
}
catch (System.Net.Mail.SmtpException ex)
{
Console.WriteLine(ex.Message, "发送邮件出错");
}
}
}
}
}