The jonki

呼ばれて飛び出てじょじょじょじょーんき

PythonでGmailを送信

以前の日記のソースがあまりにもひどかったので修正。
こんな感じでやれば送れます。

from GmailApi import *
sg = sendGmail(encoding, subject, body, from_addr, to_addr, login_addr, passwd)
sg.sendMail() # 送信


Gmail送信用に書いたクラス
◆GmailApi.py

#!/usr/bin/python
# -*- coding: utf-8 -*-

#@author jojonki
#@date 2009/05/027

#gmailでメールを送るためのSMTPライブラリ
import smtplib
from email.MIMEText import MIMEText
from email.Header import Header
from email.Utils import formatdate

class sendGmail:
def __init__(self, encoding, subject, body, from_addr, to_addr, login_addr, passwd):
self.date = formatdate()
self.encoding = encoding
self.subject = subject
self.body = body.encode('utf-8')
self.from_addr = from_addr
self.to_addr = to_addr
self.login_addr = login_addr
self.passwd = passwd

def sendMail(self):
msg = MIMEText(self.body, 'html', self.encoding)
msg['Subject'] = Header(self.subject, self.encoding)
msg['From'] = self.from_addr
msg['To'] = self.to_addr
msg['Date'] = self.date

s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(self.login_addr, self.passwd)
s.sendmail(self.from_addr, self.to_addr, msg.as_string())
s.close()