Googleアカウントのアプリパスワードを設定
[Googleアカウント][セキュリティ][Googleにログインする方法][2段階認証プロセス][アプリパスワード]
アプリ名「raspberrypi」パスワード「1234567890123456」
参考 https://support.google.com/mail/answer/185833?hl=ja
Pythonプログラムで添付ファイルを送信
EmailMessageを使用
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import smtplib
from email.message import EmailMessage
def main():
args = sys.argv
filepath = args[1]
basename = os.path.basename(filepath)
msg = EmailMessage()
msg['From'] = 'sss@gmail.com'
msg['To'] = 'ccc@gmail.com'
msg['Subject'] = basename
msg.add_alternative('本文1.', subtype='plain')
msg.add_alternative('<h1>本文2.</h1>', subtype='html')
with open(filepath, 'rb') as f:
msg.add_attachment(
f.read(),
maintype='application',
subtype='csv',
filename=basename
)
with smtplib.SMTP('smtp.gmail.com', '587') as smtp:
smtp.starttls()
smtp.login('sss@gmail.com', '1234567890123456')
smtp.send_message(msg)
if __name__ == '__main__':
main()
参考
https://qiita.com/tarao1006/items/d257299e3d202fbf4460
https://qiita.com/curry__30/items/2e487168693b8248189a
MIMETextおよびMIMEMultipartを使用(上記「EmailMessageを使用」を見ると非推奨)
単純なメール送信
プログラムをインストール
$ sudo apt -y install ssmtp mailutils
メール送信を設定
$ sudo vi /etc/ssmtp/ssmtp.conf
#root=postmaster
root=sss@gmail.com
#mailhub=mail
mailhub=smtp.gmail.com:587
#末尾に追加
AuthUser=sss@gmail.com
AuthPass=1234567890123456
UseSTARTTLS=YES
メール送信を実行
$ date | mail -s test ccc@gmail.com