Skip to content

Instantly share code, notes, and snippets.

@hnaohiro
Created January 19, 2013 10:47
Show Gist options
  • Save hnaohiro/4571949 to your computer and use it in GitHub Desktop.
Save hnaohiro/4571949 to your computer and use it in GitHub Desktop.
Gmailでメール送信をPythonで
#!/usr/bin/env python
import sys
from optparse import OptionParser
import smtplib
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate
class GMailSmtp:
def __init__(self, account, password):
self.account = account
self.password = password
def send(self, to, subject, body):
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(self.account, self.password)
msg = self.create_message(to, subject, body)
s.sendmail(self.account, to, msg.as_string())
s.close()
def create_message(self, to, subject, body, encoding='UTF-8'):
msg = MIMEText(body, 'plain', encoding)
msg['Subject'] = Header(subject, encoding)
msg['From'] = self.account
msg['To'] = ','.join(to)
msg['Date'] = formatdate()
return msg
if __name__ == '__main__':
account = 'your-account@gmail.com'
password = 'your-password'
to = 'to@exaple.com'
subject = 'subject of email'
body = 'body of email'
gmail = GMailSmtp(account, password)
gmail.send(to, subject, body)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment