HeyCHのブログ

慢性疲労のへいちゃんです

【C#】GmailのSMTPサーバーを使ってメールを送信してみよう

今回は、C#GmailSMTPサーバーを使ってメールを送信してみようという事で書いていきたいと思います。

安全性の低いアプリのアクセスをONにする

f:id:HeyCH:20200531005002p:plain

  • セキュリティをクリックし、下の方にある「安全性の低いアプリのアクセス」の「アクセスを有効にする」をクリック

f:id:HeyCH:20200531005206p:plain

  • 安全性の低いアプリの許可: 有効

f:id:HeyCH:20200531005321p:plain

コードを書く(プロジェクトはWPFアプリ)

<Window x:Class="SendEmail.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SendEmail"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="25"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="25"/>
        </Grid.RowDefinitions>
        <TextBox Grid.Row="0" Text="{Binding To}"/>
        <TextBox Grid.Row="1" Text="{Binding Subject}"/>
        <TextBox Grid.Row="2" Text="{Binding Message}"/>
        <Button Grid.Row="3" Content="Send Email" Click="Button_Click"/>
    </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SendEmail {
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window {
        ViewModel vm = new ViewModel();
        public MainWindow() {
            InitializeComponent();
            this.DataContext = vm;
        }

        private void Button_Click(object sender, RoutedEventArgs e) {
            MailMessage msg = new MailMessage();
            msg.From = new MailAddress("送信元アドレス", "アドレス名");//適宜変更してください
            msg.To.Add(new MailAddress(vm.To, ""));
            msg.Subject = vm.Subject;
            msg.Body = vm.Message;

            SmtpClient sc = new SmtpClient();

            sc.Host = "smtp.gmail.com";
            sc.Port = 587;//465じゃダメ。タイムアウトになる
            sc.EnableSsl = true;
            sc.Credentials = new System.Net.NetworkCredential("gmailアドレス", "パスワード");//適宜変更してください

            try {
                sc.Send(msg);
                MessageBox.Show("メールを送信しました");
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            } finally {
                msg.Dispose();
                sc.Dispose();
            }
        }
    }
    public class ViewModel : INotifyPropertyChanged {
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string name) {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
        string _To = "";
        public string To {
            get { return _To; }
            set {
                _To = value;
                OnPropertyChanged("To");
            }
        }
        string _Subject = "";
        public string Subject {
            get { return _Subject; }
            set {
                _Subject = value;
                OnPropertyChanged("Subject");
            }
        }
        string _Message = "";
        public string Message {
            get { return _Message; }
            set {
                _Message = value;
                OnPropertyChanged("Message");
            }
        }
    }
}