7 Nov 2010

python发送邮件


Update:可以使用下面的函数来发信

def SendEmail(fromEmail, password, toEmailList, subjectStr, contentStr):
    import smtplib
    import email.utils
    from email.mime.text import MIMEText

    # Create the message
    msg = MIMEText(contentStr)
    msg['To'] = email.utils.formataddr(('Recipient', ','.join(toEmailList)))
    msg['From'] = email.utils.formataddr(('Author', fromEmail))
    msg['Subject'] = subjectStr

    # Create the connection
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.set_debuglevel(True)  # show communication with the server
    try:
        # identify ourselves, prompting server for supported features
        server.ehlo()

        # If we can encrypt this session, do it
        if server.has_extn('STARTTLS'):
            server.starttls()
            server.ehlo()  # re-identify ourselves over TLS connection

        server.login(fromEmail, password)
        server.sendmail(fromEmail, toEmailList, msg.as_string())
    finally:
        server.quit()

为了刷签证结果,我每天刷十几次,于是写了脚本来模拟浏览器访问网站得到处理结果,具体见:python模拟网页填表.但是还是害怕漏掉,firefox有webmail notifier插件,于是想完善上个脚本,如果处理结果不是"正在处理当中",就给我邮箱发一封信,这样用死循环,每5分钟刷新一次,直到出结果邮件发送成功再break.网上一搜,发邮件的代码大把,无奈都是08年居多,竟然都不能成功,大多死在sendmail步骤,貌似是socket超时了.底层不懂啊,继续google,找到了如下代码,经测试好用.贴出来,记录之.



## 中文邮件需要加这一行指定编码
## # -*- coding: cp936 -*-

import smtplib

# Prameters
fromaddr = 'xxx@gmail.com'
## 如果多个地址,写成列表
## ['email1','email2'...]
toaddrs  = 'xxx@gmail.com'
msg = '你想发送的内容!!!'

## 如果要复杂的内容就这样指定
##sbj = "信的标题,subject!!!"
##ctt = "信的内容,content!"
##msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s"
##       % (fromaddr, ", ".join(toaddrs), sbj, ctt))


# Credentials (if needed)
username = 'xxx@gmail.com'
password = 'xxxxxx'

# The actual mail send
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.ehlo()
server.login(username,password)
## 虽然gmail可以正确解码中文,但是hotmail收到中文邮件会是乱码,解决办法就是
## 解码后按照utf8编码发送
server.sendmail(fromaddr, toaddrs, msg.decode('cp936').encode('utf8'))
server.quit()

No comments :

Post a Comment