python3发送带多张图片、附件的邮件

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_44152831/article/details/89214911

python3发送带多张图片、附件的邮件

话不多说,直接上代码,没有注释!
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.header import Header

class Mail(object):
    def __init__(self, host, nickname, username, password, postfix):
        self.host = host
        self.nickname = nickname
        self.username = username
        self.password = password
        self.postfix = postfix

    def send_mail(self, to_list, subject, content, cc_list=[], encode='gbk', is_html=True, images=[]):
        me = str(Header(self.nickname, encode)) + "<" + self.username + "@" + self.postfix + ">"
        msg = MIMEMultipart()
        msg['Subject'] = Header(subject, encode)
        msg['From'] = me
        msg['To'] = ','.join(to_list)
        msg['Cc'] = ','.join(cc_list)
        if is_html:
            mail_msg = ''
            for i in range(len(images)):
                mail_msg += '<p><img src="cid:image%d" height="240" width="320"></p>' % (i+1)
            msg.attach(MIMEText(content + mail_msg, 'html', 'utf-8'))

            for i, img_name in enumerate(images):
                with open(img_name, 'rb') as fp:
                    img_data = fp.read()
                msg_image = MIMEImage(img_data)
                msg_image.add_header('Content-ID', '<image%d>' % (i+1))
                msg.attach(msg_image)
                # 将图片作为附件
                # image = MIMEImage(img_data, _subtype='octet-stream')
                # image.add_header('Content-Disposition', 'attachment', filename=images[i])
                # msg.attach(image)
        else:
            msg_content = MIMEText(content, 'plain', encode)
            msg.attach(msg_content)

        try:
            s = smtplib.SMTP()
            # s.set_debuglevel(1)
            s.connect(self.host)
            s.login(self.username, self.password)
            s.sendmail(me, to_list + cc_list, msg.as_string())
            s.quit()
            s.close()
            return True
        except Exception as e:
            print(e)
            return False

def send_mail(to_list, title, content, cc_list=[], encode='utf-8', is_html=True, images=[]):
    content = '<pre>%s</pre>' % content
    m = Mail('smtp.163.com', 'TV-APP TEST', 'tvapp_qa', 'ujlnluutpfespgxz', '163.com')
    m.send_mail(to_list, title, content, cc_list, encode, is_html, images)


if __name__ == '__main__':
    images = [
        '1.png',
        '2.png',
        '3.png',
        '4.png',
    ]
    import time
    title = 'new images %s' % time.strftime('%H:%M:%S')
    content = 'this is attach images %s' % time.time()
    send_mail(['x@163.com'], title, content, ['xx@163.com', 'xxx@163.com'],  'utf-8', True, images)

后记

调试发送多张图片的时候遇到的最蛋疼的问题:

用for循环生成的mail_msg,不能直接attach,需要和content一起attach

mail_msg = ''
for i in range(len(images)):
    mail_msg += '<p><img src="cid:image%d" height="240" width="320"></p>' % (i+1)
    msg.attach(MIMEText(**content** + mail_msg, 'html', 'utf-8'))
展开阅读全文

jmail 发送附件邮件

06-28

<% rnEmailSender="sales@memay.com" rn'发件人名称 rnSYS_WEBNAME="sales" rn'邮件发送服务器地址 rnEMAILServer="mail.memay.com" rn'邮件发送服务器用户名 rnEMAILServerUser="sales@memay.com" rn'邮件发送服务器用户密码 rnEMAILServerPass="1234567" rntitlemessage="www.memay.com注册信息" rnrncontentmessage="您好,您在www.memay.com已经注册成功,您的登陆用户名是"&user&"密码是:"&randKey rnrnrnCall Jmail(user,titlemessage,contentmessage) rnrnrn'************************************************************************************ rn'函数名:Jmail() rnrnrn'************************************************************************************ rnrnFunction Jmail(Email,E_Subject,Information) rnDim C_Email,C_HostName,C_Smtp,C_M_User,C_M_Pass rnC_Email=EmailSender '发送者的邮箱 rnC_HostName=SYS_WEBNAME '发送者的名字 rnC_Smtp=EMAILServer 'Smtp服务器地址 rnC_M_User=EMAILServerUser '如果Smtp服务器需要验证身份,请输入用户名 rnC_M_Pass=EMAILServerPass '请输入密码 rnrnDim Sender rnErr.Clear rnOn Error Resume Next rnIf Email="" Or Information="" Or E_Subject="" Then rnJmail=False rnExit Function rnEnd If rnset Sender=Server.CreateObject("Jmail.message") rnSender.Charset="gb2312" rnSender.ISOEncodeHeaders=false rnSender.Logging=true rnSender.From=C_Email rnSender.Fromname=C_HostName rnsender.addrecipient Email rnsender.subject=E_Subject rnsender.AttachFile("E:\pearls.xls")[color=#FF0000]'这行去掉可以发送文字邮件,但我要发送附件,它提示缺少对象,不知什么原因, [/color]rnSender.AppendHtml "您好,您在www.memay.com已经注册成功,您的用户名是"&user&"密码是:"&randKey rnsender.maildomain=C_Smtp rnsender.mailserverusername=C_M_User rnsender.mailserverpassword=C_M_Pass rnsender.Priority = 3 rnsender.send(C_Smtp) rnrnset sender = nothing rnrnrnIf Err.Number <>0 Then rn Jmail=False rn Response.write "邮件发送失败!详细错误原因:"&Err.Description rnElse rn Jmail=True rn %> 论坛

没有更多推荐了,返回首页