星期二, 7月 28, 2009

python twisted sendmail

buildbot 是用 twisted library 裡的 sendmail 寄信的,方法如下:

from email.Message import Message
from twisted.mail.smtp import sendmail
from twisted.internet import defer
from twisted.internet import reactor

m = Message()
m.set_payload("Hello world!!")
m['To']="someone@somewhere.com"
m['Subject'] = "Test"
m['From'] = "my@somewhere.com"
s = m.as_string()
done = sendmail( "mailserver", "my@somewhere.com", [ "someone@somewhere.com" ], s)
done.addCallback(lambda ignored: reactor.stop())
reactor.run()


但現在大多的 mail server 都需要先認證,這時候就得改用 ESMTPSenderFactory 來改寫了(可參考Twisted mail smtp API),mailing list 裡正好有人貼出程式

from twisted.mail import smtp
from twisted.internet import reactor
from twisted.internet import defer

try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO

def sendmail_auth(smtphost, user, password,
from_addr, to_addrs, msg, senderDomainName=None, port=25):
if not hasattr(msg,'read'):
msg = StringIO(str(msg))
d = defer.Deferred()
factory = smtp.ESMTPSenderFactory(user, password, from_addr, to_addrs, msg, d,
requireTransportSecurity=False)
if senderDomainName is not None:
factory.domain = senderDomainName
reactor.connectTCP(smtphost, port, factory)
return d


再套前面的例子,只要改動 sendmail 為 sendmail_auth 就行了:程式

done = sendmail_auth( "mailserver", "your_username", "your_password", "my@somewhere.com", [ "someone@somewhere.com" ], s)

沒有留言:

您或許對這些文章有興趣

Related Posts Plugin for WordPress, Blogger...