如何用C#實現發送郵件?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
#region 發送郵件部分
private static String fromMail = "1111@126.com"; ///郵箱名稱
private static String mailPwd = "111111"; ///密碼
private static string toMail = "2222@163.com"; ///郵箱服務器
private static string fileStr;//當前圖片路徑,在添加附件時用
/// <summary>
/// 發送郵件
/// </summary>
/// <param name="fileUrl">附件地址,以~分</param>
/// <param name="screen">是否發送截屏</param>
/// <returns></returns>
public static string SendMail(string fileUrl, string screen)
{
MailAddress from = new MailAddress(fromMail);
MailAddress to = new MailAddress(toMail);
MailMessage message = new MailMessage(from, to);
message.Subject = "M郵件 " +11111;//主題
message.SubjectEncoding = System.Text.Encoding.UTF8;
Attachment attachFile = new Attachment(fileStr);
if (screen == "True")
message.Attachments.Add(attachFile);
string[] files = fileUrl.Split('~');
for (int i = 0; i < files.Length; i++)
{
if (File.Exists(files[i]))
{
Attachment attachFile1 = new Attachment(fileUrl);
message.Attachments.Add(attachFile1);
}
}
try
{
SmtpClient client = new SmtpClient("smtp." + from.Host);
SendMail(client, from, mailPwd, to, message);
return "發送郵件成功!包含附件:" + fileUrl + " 含截圖?" + screen + " " + DateTime.Now.ToString();
}
catch (SmtpException ex)
{
//如果錯誤原因是沒有找到服務器,則嘗試不加smtp.前綴的服務器
if (ex.StatusCode == SmtpStatusCode.GeneralFailure)
{
try
{
//有些郵件服務器不加smtp.前綴
SmtpClient client = new SmtpClient(from.Host);
SendMail(client, from, mailPwd, to, message);
return "發送郵件成功!包含附件:" + fileUrl + " 含截圖?" + screen + " " + DateTime.Now.ToString();
}
catch (SmtpException err)
{
return "發送郵件失??!" + err.Message + " " + DateTime.Now.ToString();
}
}
else
{
return "發送郵件失??!" + ex.Message + " " + DateTime.Now.ToString();
}
}
}
//根據指定的參數發送郵件
private static void SendMail(SmtpClient client, MailAddress from, string password,
MailAddress to, MailMessage message)
{
//不使用默認憑證,注意此句必須放在client.Credentials的上面
client.UseDefaultCredentials = false;
//指定用戶名、密碼
client.Credentials = new NetworkCredential(from.Address, password);
//郵件通過網絡發送到服務器
client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
client.Send(message);
}
catch
{
throw;
}
finally
{
//及時釋放占用的資源
message.Dispose();
}
}
#endregion關于如何用C#實現發送郵件問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。