C# 簡單傳送郵件
阿新 • • 發佈:2019-01-27
//Email 實體類
public class MyEmail
{
/// <summary>
/// 傳送方傳送方伺服器地址
/// </summary>
public string strHost { get; set; }
/// <summary>
/// 傳送方帳號
/// </summary>
public string strAccount { get; set; }
/// <summary>
/// 傳送方密碼
/// </summary>
public string strPwd { get; set; }
/// <summary>
/// 傳送方郵件地址
/// </summary>
public string strFrom { get; set; }
/// <summary>
/// 接收方郵件地址
/// </summary>
public string to { get; set; }
/// <summary>
/// 郵件標題
/// </summary>
public string title { get; set; }
/// <summary>
/// 郵件正文內容
/// </summary>
public string content { get; set; }
/// <summary>
/// 附件
/// </summary>
public string sfile { get ; set; }
}
實現方法:
//傳送Email公共方法
public class SendEmailHelp
{
/// <summary>
/// 傳送郵件
/// </summary>
/// <param name="strHost">傳送方傳送方伺服器地址</param>
/// <param name="strAccount">傳送方帳號</param>
/// <param name="strPwd">傳送方密碼</param>
/// <param name="strFrom">傳送方郵件地址</param>
/// <param name="to">接收方郵件地址</param>
/// <param name="title">郵件標題</param>
/// <param name="content">郵件正文內容</param>
/// <param name="sfile">郵件附件</param>
/// <returns></returns>
public bool sendMail(MyEmail e)//string strHost, string strAccount, string strPwd, string strFrom, string to, string title, string content
{
SmtpClient smtpClient = new SmtpClient();
if (string.IsNullOrEmpty(e.strHost))
{
e.strHost = "smtp.sina.cn";//新浪測試
}
if (string.IsNullOrEmpty(e.strAccount))
{
e.strAccount = "xxx";
}
if (string.IsNullOrEmpty(e.strPwd))
{
e.strPwd = "xxx";
}
if (string.IsNullOrEmpty(e.strFrom))
{
e.strFrom = "xxx";
}
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定電子郵件傳送方式
smtpClient.Host = e.strHost; ;//指定SMTP伺服器
smtpClient.Credentials = new System.Net.NetworkCredential(e.strAccount, e.strPwd);//使用者名稱和密碼
MailMessage mailMessage = new MailMessage(e.strFrom, e.to);
mailMessage.Subject = e.title;//主題
mailMessage.Body = e.content;//內容
mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文編碼
mailMessage.IsBodyHtml = true;//設定為HTML格式
mailMessage.Priority = MailPriority.High;//優先順序
//// 新增附件
if (e.sfile != "")
{
mailMessage.Attachments.Add(new Attachment(e.sfile));
}
try
{
smtpClient.Send(mailMessage);
mailMessage.Dispose();//釋放資源
return true;
}
catch
{
return false;
}
}
}