星期二, 1月 10, 2017

[C#] 利用 Gmail 發信

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

自訂控件 - MailAttach

UserControl 內有 Label 和 Button 兩控件
  • Label 顯示使用者傳送的檔案名稱
  • Button 則是移除該附件
  • RemoveAttachClick Event 則是方便外部了解使用者點選哪一個 Button
namespace GMail
{
    public partial class MailAttach : UserControl
    {
        public string FileFullName { get; set; }
        public string FileName { get; set; }

        public event RemoveAttachEventHandler RemoveAttachClick;

        public MailAttach(string fileFullName)
        {
            InitializeComponent();

            FileFullName = fileFullName;
            FileName = Path.GetFileName(fileFullName);
            lblFileName.Text = FileName;
        }

        private void MailAttach_Load(object sender, EventArgs e)
        {

        }

        public virtual void OnRemoveAttachClick()
        {
            if (RemoveAttachClick == null)
                return;

            RemoveAttachEventArgs e = new RemoveAttachEventArgs(FileName);
            RemoveAttachClick(this, e);
        }

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

    public delegate void RemoveAttachEventHandler(object sender, RemoveAttachEventArgs e);

    public class RemoveAttachEventArgs : EventArgs
    {
        private string _fileName;
        public string FileName => _fileName;

        public RemoveAttachEventArgs(string fileName)
        {
            _fileName = fileName;
        }
    }

}
主程式

使用 WinForm 模擬介面,要透過 Gmail 來傳送 Email 含附件

using System;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;

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

        private string _contentDefault { get; set; } = "該封為測試信";

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

            flpAttachment.FlowDirection = FlowDirection.TopDown;
            flpAttachment.AutoScroll = true;

            // 預設值
            txtGmailAccount.Text = "OOXX@gmail.com";
            txtGmailPassword.Text = "P@ssw0rd";
            txtMailTo.Text = "123@gmail.com,456@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;

            foreach (string fileFullName in fd.FileNames)
            {
                // MailAttach 為自訂控件
                MailAttach attach = new MailAttach(fileFullName);
                attach.RemoveAttachClick += Attach_RemoveAttachClick; ;
                flpAttachment.Controls.Add(attach);
            }
        }

        private void Attach_RemoveAttachClick(object sender, RemoveAttachEventArgs e)
        {
            // 移除 UI 上 flpAttachment 內的檔案
            MailAttach attach = flpAttachment.Controls.OfType<MailAttach>().Single(m => m.FileName == e.FileName);
            flpAttachment.Controls.Remove(attach);
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            MailMessage mail = new MailMessage();

            // 寄件人
            mail.From = new MailAddress(txtGmailAccount.Text.Trim(), "系統發信");
            // 收件人:
            mail.To.Add(txtMailTo.Text.Trim());

            mail.Subject = $"{txtSubject.Text.Trim()} - {DateTime.Now}";
            mail.Body = txtBody.Text.Trim();
            mail.IsBodyHtml = chkHTML.Checked;
            mail.Priority = MailPriority.Normal;

            Attachment attach;
            foreach (MailAttach mailAttach in flpAttachment.Controls.OfType<MailAttach>())
            {
                attach = new Attachment(mailAttach.FileFullName);
                attach.Name = mailAttach.FileName;
                attach.NameEncoding = Encoding.GetEncoding("UTF-8");
                mail.Attachments.Add(attach);
            }

            using (SmtpClient client = new SmtpClient("smtp.gmail.com", 587))
            {
                NetworkCredential credential = new NetworkCredential(txtGmailAccount.Text.Trim(), txtGmailPassword.Text.Trim());
                client.EnableSsl = true;
                client.Credentials = credential;

                try
                {
                    client.Send(mail);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }

            flpAttachment.Controls.Clear();
        }

        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;
        }
    }
}

實際測試


沒有留言:

張貼留言