Es ist nur eine persönliche Notiz.
#!/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('[email protected]', 'foo')
gmail.send('[email protected]', '[email protected]', 'test', 'test')
addr = '[email protected]'
mails = [{'to_addr': addr, 'from_addr': addr, 'subject': 'test', 'body': 'test'}] * 10
gmail.bulk_send(mails)