如何使用Mimemultipart在Python中发送邮件

时间:2016-01-18 07:04:25

标签: python email

我是Python的新手,因此使用python脚本发送邮件有些困难。我使用的是mime和smtplib。由于某种原因,我无法发送邮件而且我的邮件没有任何正文。代码。 任何的想法 ??

import smtplib
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart

hostname='hello'

sender = 'xx@xx.com'
receivers = ['vholla@xx.com']

msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receivers
msg['Subject'] = "Upgrade started for"+hostname+"."


try:
   smtpObj = smtplib.SMTP('mail.xxx.com',25)
   smtpObj.sendmail(sender, receivers, msg.as_string())
   print "Successfully sent email"
except:
        print "Error: unable to send email"

1 个答案:

答案 0 :(得分:1)

我有这个选项适用于postfix

import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP()
s.connect('localhost') # connect to the SMTP server
doc = "<html><h1>Test title</h1></html>"
while True:
    msg = MIMEText( doc, _subtype='html', _charset='utf-8' )
    s.sendmail('xx@xx.com', ['vholla@xx.com'], msg.as_string())
s.quit()