2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでGmail経由でメール送る

Last updated at Posted at 2019-08-18

Python、Gmail送れるソン!

send_email.py

# coding: UTF-8
import smtplib
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.utils import formatdate

from email.mime.application import MIMEApplication
from os.path import basename

# 送り元のアドレスとパスワード
FROM_ADDRESS = 'hoge@gmail.com'
PASSWORD = 'hogepass'

TO_ADDRESS = 'piyo@gmail.com'
BCC = 'poyo@gmail.com'
SUBJECT = 'Python、Gmail送れるソン!'
BODY = 'ヒクソン、ドラ〜〜ム叩くソン!'

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

    path = "./foobar.png"
    with open(path, "rb") as f:
        part = MIMEApplication(
            f.read(),
            Name=basename(path)
        )
    part['Content-Disposition'] = 'attachment; filename="%s"' % basename(path)
    msg.attach(part)

    return msg

def send(from_addr, to_addrs, msg):
    smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
    smtpobj.ehlo()
    smtpobj.starttls()
    smtpobj.ehlo()
    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)

注意

  • パスとかあってるのにログインに失敗してしまうときがある

ヒクソン、ドラ〜〜ム叩くソン!

2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?