星期二, 1月 10, 2017

[C#] 利用 Gmail 發信

學習使用 C# 利用 Gmail 來進行發信,該篇為練習範例

Gmail


GMailTool Project 是關於附加檔案,為自訂控件 - MailAttach,UserControl 內有 Label 和 Button 兩控件
  • Label 顯示使用者愈傳送的檔案名稱
  • Button 則是移除該附件
  • btnClick Event 則是方便外部了解使用者點選哪一個 Button

Gmail2

namespace GMailTool
{
    public partial class MailAttach : UserControl
    {
        private string FileName { get; set; }

        public MailAttach(string FileName)
        {
            InitializeComponent();

            this.FileName = FileName;
            this.Name = FileName;
            lblFileName.Text = FileName;
        }

        public event btnClickEventHandler btnClick;

        public virtual void OnbtnClick()
        {
            if (btnClick == null) return;

            btnClickEventArgs e = new btnClickEventArgs();
            e.FileName = this.FileName;
            btnClick(this, e);
        }

        private void btnRemoveAttach_Click(object sender, EventArgs e)
        {
            OnbtnClick();
        }
    }

    public delegate void btnClickEventHandler(object sender, btnClickEventArgs e);

    public class btnClickEventArgs : EventArgs
    {
        public string FileName { get; set; }
    }
}
Gmail Project 為主程式,要透過 Gmail 來傳送 Email 含附件

Gmail3

using System.Net;
using System.Net.Mail;
using System.IO;
using GMailTool;

namespace GMail
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        MailMessage mail = new MailMessage();
        private string ContentDefault = "該封為測試信";

        private void Form1_Load(object sender, EventArgs e)
        {
            txtGmailPassword.PasswordChar = '*';

            flowAttachment.FlowDirection = FlowDirection.TopDown;
            flowAttachment.AutoScroll = true;

            // 預設值
            txtGmailAccount.Text = "OOXX@gmail.com";
            txtGmailPassword.Text = "P@ssw0rd";
            txtMailTo.Text = "123456789@gmail.com";
            txtSubject.Text = "[C#] 利用 Gmail 發信";
            txtBody.Text = ContentDefault;
        }

        private void btnAttachment_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Multiselect = true;
            fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            if (fd.ShowDialog() != DialogResult.OK) return;

            // 把 OpenFileDialog.FileName 轉成 FileInfo,藉此找出附加檔案完整路徑
            foreach (FileInfo fi in fd.FileNames.Select(f => new FileInfo(f)).ToArray())
            {
                Attachment attach = new Attachment(fi.FullName);
                attach.Name = fi.Name;
                attach.NameEncoding = Encoding.GetEncoding("UTF-8");
                mail.Attachments.Add(attach);

                // MailAttach 為自訂控件
                MailAttach ctl = new MailAttach(fi.Name);
                ctl.btnClick += Ctl_btnClick;
                flowAttachment.Controls.Add(ctl);
            }
        }

        private void Ctl_btnClick(object sender, btnClickEventArgs e)
        {
            AttachmentRemove(e.FileName);
        }

        private void AttachmentRemove(string FileName)
        {
            // 移除 Mail 內的附加檔案
            mail.Attachments.Remove(mail.Attachments.First(m => m.Name == FileName));
            // 移除 UI 上 flowAttachment 內的檔案
            flowAttachment.Controls.Remove(flowAttachment.Controls.OfType<MailAttach>().First(m => m.Name == FileName));
        }

        private void AttachmentClear()
        {
            mail = null;
            mail = new MailMessage();
            flowAttachment.Controls.Clear();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587))
            {
                NetworkCredential c = new NetworkCredential(txtGmailAccount.Text.Trim(), txtGmailPassword.Text.Trim());
                client.EnableSsl = true;
                client.Credentials = c;

                // 寄件人
                mail.From = new MailAddress(txtGmailAccount.Text.Trim(), "系統發信");
                // 收件人
                mail.To.Add(new MailAddress(txtMailTo.Text.Trim()));
                mail.Subject = $"{txtSubject.Text.Trim()} - {DateTime.Now}";
                mail.Body = txtBody.Text.Trim();
                mail.IsBodyHtml = chkHTML.Checked;
                mail.Priority = MailPriority.Normal;

                client.Send(mail);
            }

            AttachmentClear();
        }

        private void chkHTML_CheckedChanged(object sender, EventArgs e)
        {
            string content = string.Empty;
            if (chkHTML.Checked == false)
                content = ContentDefault;
            else
                content = "<table border=1><tr><td>ID</td><td>Name</td></tr><tr><td>40</td><td>該封為測試信</td></tr></table>";

            txtBody.Text = content;
        }
    }
}

測試

Gmail4

Gmail5

沒有留言:

張貼留言