using System;
using System.Net.Mail;
using System.Net;
namespace AmwITx.Framework.Components
{
public class MailPass
{
/// <summary>
/// 发送邮件服务器
/// </summary>
public string SmtpServer { get; set; }
/// <summary>
/// 发送邮箱帐号
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 发送邮箱密码
/// </summary>
public string PassWord { get; set; }
/// <summary>
/// 发送地址
/// </summary>
public string FromMail { get; set; }
}
public class MailParameter
{
/// <summary>
/// 邮件主题
/// </summary>
public string Subject { get; set; }
/// <summary>
/// 发件人公司
/// </summary>
public string IncName { get; set; }
/// <summary>
/// 接收地址
/// </summary>
public string ToMail { get; set; }
/// <summary>
/// 抄送"邮箱名,邮箱名......"
/// </summary>
public string BccMail { get; set; }
/// <summary>
/// 邮件内容
/// </summary>
public string MailContent { get; set; }
}
public class MailService
{
/// <summary>
/// 发送邮件
/// </summary>
public static MailResult Send(MailPass pass, MailParameter parameter)
{
if (string.IsNullOrEmpty(pass.SmtpServer))
throw new Exception("parameter server not null");
var sendResult = new MailResult();
try
{
var frommail = parameter.IncName + "<" + pass.FromMail + ">";
var mail = new MailMessage(pass.FromMail, parameter.ToMail);
mail.Subject = parameter.Subject;
mail.IsBodyHtml = true;
mail.Body = parameter.MailContent;
//抄送给多人
if (!string.IsNullOrEmpty(parameter.BccMail))
{
var bccmails = parameter.BccMail.Split(',');
foreach (var bcc in bccmails)
{
mail.Bcc.Add(bcc);
}
}
mail.Sender = new MailAddress(frommail);
mail.SubjectEncoding = System.Text.Encoding.GetEncoding("utf-8");
var client = new SmtpClient(pass.SmtpServer);
client.Credentials = new NetworkCredential(pass.UserName, pass.PassWord);
client.UseDefaultCredentials = true;
client.Send(mail);
sendResult.IsSuccess = true;
}
catch (Exception ex)
{
sendResult.IsSuccess = false;
sendResult.ErrorMessage = ex.Message;
}
return sendResult;
}
}
public class MailResult
{
/// <summary>
/// 是否发送成功
/// </summary>
public bool IsSuccess { get; set; }
/// <summary>
/// 错误信息
/// </summary>
public string ErrorMessage { get; set; }
/// <summary>
/// 字符串
/// </summary>
/// <returns></returns>
public override string ToString()
{
return IsSuccess + "|" + ErrorMessage;
}
}
}