Created
April 5, 2015 01:58
-
-
Save giwa/59e5b4e351ed79222cc8 to your computer and use it in GitHub Desktop.
Python 3.4.3でgmail経由でメールを送る ref: http://qiita.com/giwa/items/f7a91b7b0439b6a958c6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment