Table of Contents
1 ローカルマシンや所属ネットワーク内でメール送信する
- ローカルマシンのみでメール送信する場合は、myhostnameをlocalhostに、mydomainをlocaldomainに設定します。
- 所属するネットワークドメインでメール送信する場合はmyhostnameをホスト名に、mydomainをドメイン名に設定します。この場合はDNSサーバを建てたり複数のマシンで共通の/etc/hostsを設定する必要があります。Postfixの設定は送信側と受信側で必要です。
以下のスクリプトを実行するとmyhostnameをlocalhostに、mydomainをlocaldomainに設定します。
#!/bin/shpostfix_install(){ cat <<EOF | sudo debconf-set-selectionspostfix postfix/main_mailer_type select No configurationEOF sudo apt install -y -o ‘apt::install-recommends=true’ postfix # shellcheck disable=SC2016 cat <<EOF | sudo tee /etc/postfix/main.cfmyhostname = ${1}mydomain = ${2}myorigin = $myhostname.$mydomainmydestination = localhost, localhost.$mydomain, $myhostname, $mydomain, $myorigincompatibility_level = 2command_directory = /usr/sbindaemon_directory = /usr/lib/postfix/sbindata_directory = /var/lib/postfixmail_owner = postfixinet_interfaces = alllocal_recipient_maps = unix:passwd.byname $alias_mapsunknown_local_recipient_reject_code = 550mynetworks_style = subnetmynetworks = 127.0.0.0/8alias_maps = hash:/etc/aliasesalias_database = hash:/etc/aliasessmtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5sendmail_path = /usr/sbin/postfixnewaliases_path = /usr/bin/newaliasesmailq_path = /usr/bin/mailqsetgid_group = postdropinet_protocols = ipv4EOF sudo newaliases sudo systemctl restart postfix sudo apt install -y mutt}postfix_main(){ postfix_install localhost localdomain # localhost only. # postfix_install ${YOUR_HOSTNAME} ${YOUR_DOMAIN} # your network.}postfix_main
2 Gmailにメール送信する
myhostnameとmydomainはローカルでも所属するネットワークドメインのどちらでも構いません。
Postfixに以下の設定を追加します。
$ cat <<EOF | sudo tee -a /etc/postfix/main.cfrelayhost = [smtp.gmail.com]:587smtp_sasl_auth_enable = yessmtp_sasl_password_maps = hash:/etc/postfix/sasl_passwdsmtp_sasl_security_options = noanonymoussmtp_sasl_mechanism_filter = plainsmtp_use_tls = yesEOF
/etc/postfix/sasl_passwdを作成します。GMAIL_ADDRにGmailのメールアドレスを([email protected])、GMAIL_PASSWDにGmailのパスワードを設定してください。
$ echo “[smtp.gmail.com]:587 ${GMAIL_ADDR}:${GMAIL_PASSWD}” | sudo tee /etc/postfix/sasl_passwd$ sudo chmod 600 /etc/postfix/sasl_passwd$ sudo postmap hash:/etc/postfix/sasl_passwd
Postfixを再起動します。
$ sudo systemctl restart postfix
このままではGmailの認証でエラーとなります。
postfix/smtp … SASL authentication failed; server smtp.gmail.com…
2段階認証でアプリケーション用のパスワードを発行するのがより良い方法だとは思いますが、ここでは安全性の低いアプリの許可を有効にします。
https://myaccount.google.com/lesssecureapps
これでもGmailの認証でエラーとなる場合は、Googleアカウントへのアクセスのを許可が必要となるかもしれません。
https://accounts.google.com/DisplayUnlockCaptcha
以上の設定を済ませることで、インターネット側のメールはGmailに送信されます。メールの差出人はGmailのアドレスとなります。
postfix/smtp … to=<[email protected]>,relay=smtp.gmail.com …