Help us understand the problem. What is going on with this article?

PythonでGmailを利用したメール送信

More than 1 year has passed since last update.

前提

環境

Name Version
Ubuntu 18.04.1 LTS (Bionic Beaver)
Python Python 3.6.7

目的

  • Pythonの標準ライブラリを用いて、ssl接続でGmailを利用してメールを送信する。

参考

送信方法

Gmailアカウントの設定

  • 送信に利用するGmailアカウントで「安全性の低いアプリのアクセス」を許可する必要がある。
  • Googleアカウント「セキュリティ」の下部にて設定する。

送信

  • 以下のサンプルコードを実行する。
send_mail.py
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate
import ssl

FROM_ADDRESS = 'sender@gmail.com'
MY_PASSWORD = 'password'
TO_ADDRESS = 'receiver@test.co.jp'
BCC = ''
SUBJECT = 'GmailのSMTPサーバ経由'
BODY = 'pythonでメール送信'


def create_message(from_addr, to_addr, bcc_addrs, subject, body):
    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = to_addr
    msg['Bcc'] = bcc_addrs
    msg['Date'] = formatdate()
    return msg


def send(from_addr, to_addrs, msg):
    #context = ssl.create_default_context()
    smtpobj = smtplib.SMTP_SSL('smtp.gmail.com', 465, timeout=10)
    smtpobj.login(FROM_ADDRESS, MY_PASSWORD)
    smtpobj.sendmail(from_addr, to_addrs, msg.as_string())
    smtpobj.close()


if __name__ == '__main__':

    to_addr = TO_ADDRESS
    subject = SUBJECT
    body = BODY

    msg = create_message(FROM_ADDRESS, to_addr, BCC, subject, body)
    send(FROM_ADDRESS, to_addr, msg)
python3 send_mail.py
nakasuke_
環境構築とアノテーションの日々
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away