iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 5
0
自我挑戰組

What a good thing we lose? What a bad thing we knew?系列 第 5

【Day 5】 在Visual Studio 2017 使用gmail發信

大家好,今天跟大家學習如何寫一隻利用gmail發信的程式,請大家不要拿去發垃圾信喔。

在開始寫程式之前,提醒大家 這隻程式會降低gmail的安全度,因此大家在使用時,要注意資安

本文開始:

Step 1 先using 使用的類別

using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

Step 2 寫一個寄信的Function

 public void SendEmail()
    {
        //設定smtp主機
        string smtpAddress = "smtp.gmail.com";
       
        //設定Port
        int portNumber = 587;
       
        bool enableSSL = true;
        //填入寄送方email和密碼
        string emailFrom = "youremail@gmail.com";
        string password = "yourpassword";
       

        //收信方email
        string emailTo = "eim24400@nbzmr.com";
        //主旨
        string subject = "Hello";
        //內容
        string body = "TEST,ithome";

        using (MailMessage mail = new MailMessage())
        {
            mail.From = new MailAddress(emailFrom);
            mail.To.Add(emailTo);
            mail.Subject = subject;
            mail.Body = body;
            // 若你的內容是HTML格式,則為True
            mail.IsBodyHtml = false;

         
            using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
            {
                smtp.Credentials = new NetworkCredential(emailFrom, password);
                smtp.EnableSsl = enableSSL;
                smtp.Send(mail);
            }
        }
    }
    

Step 3. 登入gmail後, 進入:https://myaccount.google.com/lesssecureapps 修改權限 (改成啟用)
https://ithelp.ithome.com.tw/upload/images/20181019/20112000vTTDdm9Btt.png

Step 4. 將發信的Function 放在Controller
https://ithelp.ithome.com.tw/upload/images/20181019/20112000Yl2o2xqKVU.png

Step5. View

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

寄信成功

Step6. 開啟Index
https://ithelp.ithome.com.tw/upload/images/20181019/20112000WytXvl0Co1.png

Step7. 看看是否成功

https://ithelp.ithome.com.tw/upload/images/20181019/20112000gkkgXWXS5d.png

https://ithelp.ithome.com.tw/upload/images/20181019/201120007pBtlCt5Dz.png

然後因為明天是難得的假日,所以假日發的文章內容可能會相對偷懶XD


上一篇
【Day 4】 在Visual Studio 2017 建立身分證驗證器
下一篇
【Day 6】 使用JavaScript 做字串處理
系列文
What a good thing we lose? What a bad thing we knew?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言