Created
January 19, 2013 10:47
-
-
Save hnaohiro/4571949 to your computer and use it in GitHub Desktop.
Gmailでメール送信をPythonで
This file contains hidden or 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/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 = '[email protected]' | |
password = 'your-password' | |
to = '[email protected]' | |
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