using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
namespace MailTest
{
public class AkMail
{
public AkMail() { }
public AkMail(string from, string fromName, string recipient, string recipientName, string subject, string body, string host, string port, string username, string password, bool isBodyHtml, string filepath)
{
}
#region 属性
private string _subject;
private string _body;
private string _from;
private string _fromName;
private string _recipientName;
private string _serverHost;
private int _serverPort;
private string _usrename;
private string _password;
private bool _isBodyHtml;
private string _recipient;
private List<string> _attachment = new List<string>();
private string _errMsg;
public string Subject { get => _subject; set => _subject = value; }
public string Body { get => _body; set => _body = value; }
public string From { get => _from; set => _from = value; }
public string FromName { get => _fromName; set => _fromName = value; }
public string RecipientName { get => _recipientName; set => _recipientName = value; }
public string ServerHost { get => _serverHost; set => _serverHost = value; }
public int ServerPort { get => _serverPort; set => _serverPort = value; }
public string Usrename { get => _usrename; set => _usrename = value; }
public string Password { get => _password; set => _password = value; }
public bool IsBodyHtml { get => _isBodyHtml; set => _isBodyHtml = value; }
public string Recipient { get => _recipient; set => _recipient = value; }
public List<string> Attachment { get => _attachment; set => _attachment = value; }
public string ErrMsg { get => _errMsg; set => _errMsg = value; }
#endregion
public bool Send()
{
MailMessage mail = new MailMessage();
Encoding encoding = Encoding.GetEncoding("utf-8");
mail.From = new MailAddress(From, FromName, encoding);
mail.To.Add(new MailAddress(Recipient, RecipientName));
mail.Subject = Subject;
mail.IsBodyHtml = IsBodyHtml;
mail.Body = Body;
mail.Priority = MailPriority.Normal;
mail.BodyEncoding = encoding;
if (Attachment.Count > 0)
foreach (string file in Attachment)
mail.Attachments.Add(new Attachment(file));
SmtpClient smtp = new SmtpClient();
smtp.Host = ServerHost;
smtp.Port = ServerPort;
if (smtp.Port != 25)
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential(Usrename, Password);
try
{
smtp.Send(mail);
return true;
}
catch (Exception ex)
{
string message = ex.Message;
return false;
}
}
public string SendTest()
{
var mail = new AkMail()
{
Subject = "测试邮件",
From = "xxx",
FromName = "xxx",
Recipient = "xxx",
RecipientName = "xxx",
Usrename = "xxx",
Password = "xxx",
ServerHost = "xxx",
ServerPort = 25,
};
if (mail.Send())
return "ok";
else
return mail.ErrMsg;
}
}
}