栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 发邮件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 发邮件

继续修改上面一节的发邮件代码

发送附件:

(1)先找一个本地的文件

(2)打开文件,读出文件字符串

(3)通过MIMT ext()类来创建一个对象att,传入文件读出内容

(4)增加att的头部信息,并指定文件名字

(5)添加到msg消息中msg.attach(att)

样例:

attfile = 'test.py'

basename = os.path.basename(attfile)

fp = open(attfile, 'rb')

att = email.mime.text.MIMEText(fp.read(), 'html', 'utf-8')

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

att.add_header('Content-Disposition', 'attachment',filename=('utf-8', '', basename))#three-tuple of (charset, language, value),

# encoders.encode_base64(att)

msg.attach(att)


发送图片:

(1)本地必须存在一张图片;

(2)打开图片,并读取图片内容

(3)创建发邮件相对应的图片对象imgattr = MIMEImage(fimg.read())

(4)增加图片的头信息, imgattr.add_header('Content-ID', '')

指定了图片的id,图片如果想在正文中显示,必须通过html的格式显示出来:在前端代码中指定图片id

添加到message的信息中


所以 message.conf 修改为:

vim message.conf

From = 2899@qq.com

To = 2799@qq.com, 10701@qq.com

Cc = 2399@qq.com

Subject = 测试邮件

File = 1.txt,2.txt

 

Image = 1.jpg,2.jpg

message = '''大家好:

    测试邮件

    测试邮件

以上

谢谢

 

#以下是HTML文件信息:

hello world

hello world

hello world

hello world

hello world

hello world

   

       

           

           

       

   

   

       

           

           

       

       

           

           

       

   

IPDNS BOOL
1.1.1.1True
2.2.2.2False

 

 

 

#引入图片:

漫游:

枪手:

'''



把发邮件的代码封装起来,添加抄送人(Cc),添加附件(File),util.py 不做改动

vim sendmail2.py

import codecs

import email.mime.multipart

import email.mime.text

import email.header

import os

from email.mime.image import MIMEImage

from util import getProperty

import smtplib

 

 

class SendMail(object):

    def __init__(self):

        self.sendFrom = getProperty("From")

        self.sendTo = getProperty("To").split(",")

        self.connect = getProperty("message")

        self.sendCc = getProperty("Cc").split(",")

        self.sendFile = list()

        self.sendImage = list()

 

        for i in getProperty("File").split(","):

            self.sendFile.append(i.replace("r", ""))

        for j in getProperty("Image").split(","):

            self.sendImage.append(j.replace("r", ""))

 

        self.msg = None

 

    def setEmailHeader(self):

        self.msg = email.mime.multipart.MIMEMultipart()

        self.msg['from'] = self.sendFrom

        self.msg['to'] = ";".join(self.sendTo)

        self.msg['cc'] = ";".join(self.sendCc)

        self.msg['subject'] = email.header.Header(getProperty("Subject"))

 

    def setMessage(self):

        text = email.mime.text.MIMEText(self.connect, 'html', 'utf-8')

        self.msg.attach(text)

 

    def setFile(self):

        for file in self.sendFile:

            if os.path.exists(file):

                with codecs.open(file, "rb") as f:

                    attr = email.mime.text.MIMEText(str(f.read()), "html", "utf-8")

                attr["Content-Type"] = 'application/octet-stream'

                attr.add_header('Content-Disposition', 'attachment',filename=('utf-8', '', file))

                self.msg.attach(attr)

            else:

                print ("{0} file is not exists!".format(file))

 

    def setImage(self):

        start = 1

        for image in self.sendImage:

            if os.path.exists(image):

                with codecs.open(image, "rb") as I:

                    attrImage = MIMEImage(I.read())

                    attrImage.add_header('Content-ID', ''.format(int(start)))

                    self.msg.attach(attrImage)

                    start += 1

            else:

                print("{0} image is no exists!".format(image))

 

 

    def sendemailLast(self):

        smtp = smtplib.SMTP_SSL("smtp.qq.com", 465)

        #smtp.set_debuglevel(1)

        #print (self.sendFrom)

        smtp.login(self.sendFrom, 'xrutyyjbcaae')

        #print (self.sendTo)

        smtp.sendmail(self.sendFrom, self.sendTo + self.sendCc, self.msg.as_string())

 

def main():

    sendMail = SendMail()

    sendMail.setEmailHeader()

    sendMail.setMessage()

    sendMail.setFile()

    sendMail.setImage()

    sendMail.sendemailLast()

 

if __name__ == '__main__':

    main()



同级的文件目录


执行结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/225433.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号