python: send email with pictures

Strong recommendation: Python recipes , which clearly explain how python sends emails with pictures.

I happen to have a demand, so I send an email in the form of a web page, and there are pictures on the web page.

Below is my own code for sending a mail with an image:

def send_email(subject, to_address_list, cc_address_list):
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.header import Header
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage

    sendObj = smtplib.SMTP('mail.gometech.com.cn', 25)
    sendObj.set_debuglevel(1)  # 打印debug日志
    print(sendObj)  # ok 了
    # 2. 跟服务器建立连接
    sendObj.ehlo()
    # 3. 实现加密的必须的步骤
    # sendObj.starttls()

    username = r'[email protected]'
    password = _get_password()

    # ##########################--------------- start
    # 读取html文件内容
    f = open('e:/py/notification.html', 'r', encoding='utf-8')
    mail_body = f.read()
    f.close()

    # 00. 类型需要是 multipart 的
    msg = MIMEMultipart('related')
    msg['To'] = ",".join(to_address_list)
    msg['Cc'] = ",".join(cc_address_list)
    msg['Subject'] = Header(subject, 'utf-8').encode()

    # 01. 添加文本
    msgText = MIMEText(mail_body.replace('{username}', newly_gerrit()), _subtype='html', _charset='utf-8')
    msg.attach(msgText)
    # 02. 添加图片
    file = open("e:/py/dns.jpg", "rb")
    img_data = file.read()
    file.close()
    img = MIMEImage(img_data)
    img.add_header('Content-ID', 'dns_config') 
    msg.attach(img)

    login_result = sendObj.login(username, password)
    # 4. 发送邮件
    send_result = sendObj.sendmail(username, to_address_list + cc_address_list,
                                   msg.as_string())
    # 5. 发送完成,退出
    quit_result = sendObj.quit()
    print(login_result, send_result, quit_result)

important point:

msg = MIMEMultipart('related')This type must be selected, otherwise it cannot contain both pictures and text. msgIt is equivalent to a container, which itself has no specific content. If you want something, call msg.attach(msgText)this method to include it.

# 02. 添加图片
file = open("e:/py/dns.jpg", "rb")
img_data = file.read()
file.close()
img = MIMEImage(img_data)
img.add_header('Content-ID', 'dns_config') # todo: 注意这里的 dns_config 是和 html中对应的
msg.attach(img)

The corresponding code htmlin :

<img src="cid:dns_config" alt="dns配置"> 
<!--todo: src 不是一个路径了,而是 cid:dns_config 这样的一个东西 -->

In general, that's about it, kneel down.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324724676&siteId=291194637