はじめに
Pythonプログラムからgmailを送信する方法をご紹介します。
認証は簡単ですし程よく無視できるので、自分しか使用しない場合にGmailでの通知は非常に便利です。
最後にプログラム全文を載せています。
使用するライブラリ
組み込みなので pip install
の類は不要です。
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
main()
から各メソッドを呼び出します
def main():
img_path = 'sample.png'
message = setup_mail()
message = attach_img(message, img_path)
send_mail(message)
return
def setup_mail():
message = MIMEMultipart()
message["Subject"] = "メールの件名です"
message["To"] = '送信先@hogehoge.com'
message["From"] = '送信元@gmai.com'
message.attach(MIMEText('メール本文', "html"))
return message
smtplibモジュールを使ってgoogleにログインし、send_message
メソッドに、情報を添加したMIMEMultipart()
を渡すことでメールを送信します。
def send_mail():
account = 'hogehge.gmail.com'
password = 'パスワード'
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(account, password)
server.send_message(message)
server.quit()
画像を添付する場合は、画像を読み込みMIMEImage
に渡します。
def attach_img(message, img_path=None):
if img_path is None: # 画像のpathを渡さなかった場合、画像を添付しない
return
with open(img_path, 'rb') as f:
img = f.read()
image = MIMEImage(img, name=img_path)
message.attach(image)
return
Google の二段階認証設定方法
送信元のGoogle アカウントで以下へアクセスして二段階認証をオン
https://myaccount.google.com/signinoptions/two-step-verification
次に、以下よりメールを選択、生成をクリック
https://myaccount.google.com/apppasswords
パスワードを控えておきます。
send_mail()内のpasswordとして使用します。
以下プログラム全文
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
GMAIL = '' # 上記でパスワードを発行したアカウントアドレスを記入
PASSWORD = ''
MAIL_TO = ''
def main(mail_to, subject, mail_body, img_path=None):
message = setup_mail(subject, mail_to, mail_body)
attach_img(message, img_path)
send_mail(message)
return
def setup_mail(subject, mail_to, mail_body):
message = MIMEMultipart()
message["Subject"] = subject
message["To"] = mail_to
message["From"] = GMAIL
message.attach(MIMEText(mail_body, "html"))
return message
def send_mail(message):
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login(GMAIL, PASSWORD)
server.send_message(message)
server.quit()
def attach_img(message, img_path):
if img_path is None:
return
with open(img_path, 'rb') as f:
img = f.read()
image = MIMEImage(img, name=img_path)
message.attach(image)
return
if __name__ == '__main__':
main(MAIL_TO, 'タイトルです', '本文です')
# 画像添付
main(MAIL_TO, 'タイトルです', '本文です'img_path='sample.png')