使用python发送邮件

使用python能够非常方便的发送邮件。只需要引入smtplib这个模块即可。下面是简单的示例代码:

import smtplib
from email.mime.text import MIMEText
from email.header import Header

mail_host="smtp.sendhost.com"
mail_user="sender@sendhost.com"
mail_pass="sender_password"

sender = 'send@receivehost.com'
receivers = ['receive@areceivehost.com']


def sendMail(content):
    message = MIMEText(content, 'plain', 'utf-8')
    message['From'] = Header("send_name", 'utf-8')
    message['To'] = Header("receive_name", 'utf-8')

    subject = 'sample_title'
    message['Subject'] = Header(subject, 'utf-8')

    try:
        smtpObj = smtplib.SMTP_SSL()
        #smtpObj.set_debuglevel(1)
        smtpObj.connect(mail_host, 465)
        smtpObj.login(mail_user,mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print "Send Mail Succeed"
    except smtplib.SMTPException:
        print "Error: Send Mail Failed"

如果使用非SSL方式则使用smptlib.SMTP()方法。

暂无评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注