1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

RaspberryPiからGmailの送信サーバーを使う

Last updated at Posted at 2024-03-21

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を使用」を見ると非推奨)

参考 http://make.bcde.jp/python/gmail%E3%81%A7%E7%B0%A1%E5%8D%98%E3%81%AB%E3%83%A1%E3%83%BC%E3%83%AB%E9%80%81%E4%BF%A1/

単純なメール送信

プログラムをインストール

$ 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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?