C#使用QQ郵箱SMTP服務發送郵件

開啓郵箱的SMTP服務

進入QQ郵箱->設置->賬戶->開啓POP3/SMTP服務,通過發短信開通後會獲取一個授權碼,記得保存授權碼,在程序中要使用
在這裏插入圖片描述
在這裏插入圖片描述

郵件發送代碼


/// <summary>
/// 發送郵件
/// </summary>
private string sendEmail()
{
    try
    {
        //發送者郵箱賬戶
        string sendEmail = "[email protected]";
        //發送者郵箱賬戶授權碼
        string code= "xxxxxxxxxxxxxxxx";
        //發件人地址
        MailAddress from = new MailAddress(sendEmail);
        MailMessage message = new MailMessage();
        
        //收件人地址
        message.To.Add("[email protected]");
        
        //標題
        message.Subject = "smtp發送郵件標題";
        message.SubjectEncoding = Encoding.UTF8;
        message.From = from;
      	
      	//郵件內容
        message.Body = "smtp發送郵件內容";
        message.IsBodyHtml = true;
        message.BodyEncoding = Encoding.UTF8;
        
        SmtpClient client = new SmtpClient();
        client.EnableSsl = true;
        client.Host = "smtp.qq.com";//smtp服務器
        client.Port = 587;//smtp端口
        
        //發送者郵箱賬戶和授權碼
        client.Credentials = new NetworkCredential(sendEmail, code);
        client.Send(message);
        
        return "發送成功";
    }
    catch (Exception e)
    {
        return e.ToString();
    }
}

ps:

可以配合winform / web 應用程序使用(不喜歡命令行的童鞋)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章