python发送邮件(普通,富文本,带多附件)_SSL

#信息
#发送人以及邮件服务器信息
SenderInfo = {
    "host" : "smtp.qq.com",
    "user" : "815787213@qq.com",
    "passwd" : "**********",    #你的授权码
    "from" : "Dcp<815787213@qq.com>",
    "postfix" : "qq.com"
}

#接收人
Receivers=["815787213@qq.com"]

获取邮件的信息

def get_msg(msg_type):
    msg=None
    if msg_type == 1:    #普通邮件
        msg = MIMEText("Can I get your money?",_subtype='plain')
        msg["Subject"] = "Your Money is Coming..."
        name="Someone"
        msg["From"]=formataddr(
            (Header(name,"utf-8").encode(),"%s@%s"%(SenderInfo["user"],SenderInfo['postfix']))
        )
        msg['To']=";".join(Receivers)
    elif msg_type == 2:    #富文本邮件
        content="""
        <!DOCTYPE html>
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html";charset="utf-8">
        <title>Dcp's python email</title>
        </head>
        <body>
        <p>Dcp's babys:</p>
        <p><h1>Happy New Year!</h1></p>
        </body>
        </html>
        """
        msg = MIMEText(content,_subtype='html')
        msg["Subject"] = "Your Red Bag is Coming.."
        name="Money"
        msg["From"]=formataddr(
            (Header(name,"utf-8").encode(),"%s@%s"%(SenderInfo["user"],SenderInfo['postfix']))
        )
        msg['To'] = ";".join(Receivers)
    elif msg_type == 3:    #带附件的Email
        msg = MIMEMultipart()
        name="Money"
        msg["Subject"] = "Your Money is Coming..."
        msg["From"] = formataddr(
            (Header(name, "utf-8").encode(), "%s@%s" % (SenderInfo["user"], SenderInfo['postfix']))
        )
        msg['To'] = ";".join(Receivers)
        # msg.attach(MIMEText("Your Red Bag is Coming...","plain","utf-8"))
        # att1 = MIMEBase('application','pdf',filename=('utf-8','','Red_Bag.pdf'))
        # att1.add_header('Content-Disposition','attachment',filename=('gb2312','','Red_bag.pdf'))
        # att1.add_header('Content-ID',<0>)
        # att1.add_header('X-Attachment_Id','0')
        # att1.set_payload(open('Red_Bag.pdf','rb').read())
        # encode_base64(att1)
        # msg.attach(att1)
        # att2=MIMEText(open('Red_Bag.txt','rb').read(),'base64','utf-8')
        # att2["Content-Type"]='application/octet-stream'
        # att2["Content-Disposition"]="attachment";filename="Red_bage.txt"
        # msg.attach(att2)
        with open('Red_bag.png','rb') as f:
            att3 = MIMEBase('image','png',filename='Red_Bag.png')
            att3.add_header('Content-Disposition','attachment',filename='Red_Bag.png')
            att3.add_header('Content-ID','<0>')
            att3.add_header('X-Attachment-Id','0')
            att3.set_payload(f.read())
            encode_base64(att3)
            msg.attach(att3)
    return msg

发送邮件

def Send_Email(receivers,sender_info,messages):
    try:
        server = SMTP_SSL()
        server.connect(sender_info["host"])
        server.login(sender_info["user"],sender_info["passwd"])
        server.sendmail(sender_info["from"],receivers,messages.as_string())
        server.close()
        return True
    except Exception as e:
        print (str(e))
        return False

主函数:

if __name__=="__main__":
    for i in range(1,4):
        msg=get_msg(i)
        ret=Send_Email(Receivers,SenderInfo,msg)
        print ("Massage Send %s"%("Successfully" if ret else "Faild."))

完整代码:

from smtplib import SMTP_SSL
from email.encoders import encode_base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.header import Header
from email.utils import formataddr

SenderInfo = {
    "host" : "smtp.qq.com",
    "user" : "815787213@qq.com",
    "passwd" : "*********",    #你的授权码
    "from" : "Dcp<815787213@qq.com>",
    "postfix" : "qq.com"
}

# Receivers=["815787213@qq.com","1829182801","121930043@qq.com","2376020104@qq.com","1748436449@qq.com"]
Receivers=["815787213@qq.com"]

def Send_Email(receivers,sender_info,messages):
    try:
        server = SMTP_SSL()
        server.connect(sender_info["host"])
        server.login(sender_info["user"],sender_info["passwd"])
        server.sendmail(sender_info["from"],receivers,messages.as_string())
        server.close()
        return True
    except Exception as e:
        print (str(e))
        return False

def get_msg(msg_type):
    msg=None
    if msg_type == 1:
        msg = MIMEText("Can I get your money?",_subtype='plain')
        msg["Subject"] = "Your Money is Coming..."
        name="Someone"
        msg["From"]=formataddr(
            (Header(name,"utf-8").encode(),"%s@%s"%(SenderInfo["user"],SenderInfo['postfix']))
        )
        msg['To']=";".join(Receivers)
    elif msg_type == 2:
        content="""
        <!DOCTYPE html>
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html";charset="utf-8">
        <title>Dcp's python email</title>
        </head>
        <body>
        <p>Dcp's babys:</p>
        <p><h1>Happy New Year!</h1></p>
        </body>
        </html>
        """
        msg = MIMEText(content,_subtype='html')
        msg["Subject"] = "Your Red Bag is Coming.."
        name="Money"
        msg["From"]=formataddr(
            (Header(name,"utf-8").encode(),"%s@%s"%(SenderInfo["user"],SenderInfo['postfix']))
        )
        msg['To'] = ";".join(Receivers)
    elif msg_type == 3:
        msg = MIMEMultipart()
        name="Money"
        msg["Subject"] = "Your Money is Coming..."
        msg["From"] = formataddr(
            (Header(name, "utf-8").encode(), "%s@%s" % (SenderInfo["user"], SenderInfo['postfix']))
        )
        msg['To'] = ";".join(Receivers)
        # msg.attach(MIMEText("Your Red Bag is Coming...","plain","utf-8"))
        # att1 = MIMEBase('application','pdf',filename=('utf-8','','Red_Bag.pdf'))
        # att1.add_header('Content-Disposition','attachment',filename=('gb2312','','Red_bag.pdf'))
        # att1.add_header('Content-ID',<0>)
        # att1.add_header('X-Attachment_Id','0')
        # att1.set_payload(open('Red_Bag.pdf','rb').read())
        # encode_base64(att1)
        # msg.attach(att1)
        # att2=MIMEText(open('Red_Bag.txt','rb').read(),'base64','utf-8')
        # att2["Content-Type"]='application/octet-stream'
        # att2["Content-Disposition"]="attachment";filename="Red_bage.txt"
        # msg.attach(att2)
        with open('Red_bag.png','rb') as f:
            att3 = MIMEBase('image','png',filename='Red_Bag.png')
            att3.add_header('Content-Disposition','attachment',filename='Red_Bag.png')
            att3.add_header('Content-ID','<0>')
            att3.add_header('X-Attachment-Id','0')
            att3.set_payload(f.read())
            encode_base64(att3)
            msg.attach(att3)
    return msg


if __name__=="__main__":
    for i in range(1,4):
        msg=get_msg(i)
        ret=Send_Email(Receivers,SenderInfo,msg)
        print ("Massage Send %s"%("Successfully" if ret else "Faild."))

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值