LoginSignup
4
4

More than 5 years have passed since last update.

Python 3.4.3でgmail経由でメールを送る

Posted at

個人的なメモ程度です。


#!/usr/bin/python

import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formatdate

class Gmail:
    """
    Gmail with smtp client
    """
    def __init__(self, login_addr, passwd, encoding='utf-8'):
        self._encoding = encoding
        self._login_addr = login_addr
        self._passwd = passwd

    def send(self, to_addr, from_addr, subject, body):
        """
        Send a mail via gmail
        """
        msg = self._format_email(to_addr, from_addr, subject, body)
        with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
            stmp.ehlo()
            stmp.starttls()
            stmp.ehlo()
            stmp.login(self._login_addr, self._passwd)
            stmp.sendmail(from_addr, to_addr, msg.as_string())

    def _format_email(self, to_addr, from_addr, subject, body):
        msg = MIMEText(body, 'html', self._encoding)
        msg['Subject'] = Header(subject, self._encoding)
        msg['From'] = from_addr
        msg['To'] = to_addr
        msg['Date'] = formatdate()

        return msg

    def bulk_send(self, emails):
        """
        Send multiple mails at one time via gmail
        """
        with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
            smtp.ehlo()
            smtp.starttls()
            smtp.ehlo()
            smtp.login(self._login_addr, self._passwd)
            for email in emails:
                msg = self._format_email(email['to_addr'], email['from_addr'],
                                         email['subject'], email['body'])
                smtp.sendmail(email['from_addr'], email['to_addr'],
                              msg.as_string())


if __name__ == "__main__":
    gmail = Gmail('hoge@gmail.com', 'foo')
    gmail.send('foo@gmail.com', 'bar@gmail.com', 'test', 'test')
    addr = 'baz@gmail.com'
    mails = [{'to_addr': addr, 'from_addr': addr, 'subject': 'test', 'body': 'test'}] * 10
    gmail.bulk_send(mails)




4
4
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
4
4