广州linux

当前位置:   网站首页 >> python

Python发送邮件 Python发送邮件代码

smtplib进行邮箱服务器登陆、发送邮件

MIMEText发送普通的文本邮件,为避免正文乱码,MIMEText初始化需使用utf-8编码,标题采用Unicode编码

MIMEMultipart发送附件,附件的路径需要用GBK编码


# coding=utf8

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

import smtplib

import sys


reload(sys)

sys.setdefaultencoding('utf-8')


mail_host = 'smtp.qq.com' # 邮箱服务器

me = 'XXXX'  # 发件邮箱,必须和登陆邮箱相同

mail_user = 'XXXX'  # modify

mail_key = 'XXXX'  # modify


'''

    mailto  # 收件人列表

    mailcc  # 抄送人列表

    sub     # 邮件主题

    cont    # 邮件内容

'''

def send_mail(mailto, mailcc, sub, cont):

    msg = MIMEText(cont, _subtype='plain', _charset='utf8')


    msg['subject'] = unicode(sub)  # subjuct must encode by unicode

    msg['From'] = me

    msg['To'] = ';'.join(mailto)

    msg['Cc'] = ';'.join(mailcc)

    msg['Accept-language'] = "zh-CN"

    msg['Accept-Charset'] = "ISO-8859-1, utf-8"

    print send(mailto, msg)


def send_attach(mailto, mailcc, sub, path):

    msg = MIMEMultipart()

    att = MIMEText(open(str(path).encode('GBK'), 'rb').read(), 'base64', 'utf-8')

    att['Content-Type'] = 'application/octet-stream'

    att["Content-Disposition"] = 'attachment; filename="attachname.png"'  # 你的附件名称


    msg.attach(att)

    msg['subject'] = unicode(sub)  # subjuct must encode by unicode

    msg['From'] = me

    msg['To'] = ';'.join(mailto)

    msg['Cc'] = ';'.join(mailcc)

    print send(mailto, msg)


def send(to, msg):

    try:

        s = smtplib.SMTP()

        s.connect(mail_host)

        s.login(mail_user, mail_key)

        s.sendmail(me, to, msg.as_string())

        s.close()

        return True

    except Exception, e:

        print e

        return False


def run():

    mail_to_list = ['10000@qq.com', '123456@qq.com']

    mail_cc_list = ['abc@qq.com', 'aaa@qq.com']

    subject = '邮件主题'

    content = '邮件内容'

    path = '/Users/bin/Desktop/emailtest.png' # 附件路径

    send_mail(mail_to_list, mail_cc_list, subject, content)

    send_attach(mail_to_list, mail_cc_list, subject, path)


run()


发表我的评论

Hi,您需要填写昵称和邮箱!

  • 必填项