Python SMTPlib/Email

Posted on February 13, 2018

I followed the instruction which is written in Chinese to learn how to send emails by Python, here some tips from my practice:

  1. Name of the attachment is shown as ‘ATT00002’

    The name of the attachment in the receiver mailbox is shown in the format ‘ATT0000X‘ with the code:

    att1["Content-Disposition"] = 'attachment; filename="runoob.txt"'
    
    Issue
    Issue

    The issue can be fixed by using .addheader() function:

    att1.add_header('Content-Disposition', 'attachment', filename="1.cpp")
    

Here is my code:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.header import Header
from email.utils import formataddr
sender = "mySendEmail1"
receiver = "myRecEmail1"
pwd = 'mypwd'
ret = True
mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.runoob.com">这是一个链接</a></p>
<p><img src="cid:image1"></p>
"""
msg = MIMEMultipart()
msg['From'] = formataddr(['kz', sender])
msg['To'] = formataddr(['Dear Customer', receiver])
msg['Subject'] = Header('Test Email', 'utf-8')
msg.attach(MIMEText(mail_msg, 'html', 'utf-8'))
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)
att1 = MIMEText(open('1.cpp', 'rb').read(), 'base64', 'utf-8')
att1['Context-Type'] = 'application/octet-stream'
att1.add_header('Content-Disposition', 'attachment', filename="1.cpp")
msg.attach(att1)
server = smtplib.SMTP('smtp-mail.outlook.com', 587)
server.starttls()
try:
server.login(sender, pwd)
server.sendmail(sender, [receiver ,], msg.as_string())
server.quit()
except Exception:
print(Exception)
ret = False
if ret:
print('Email has been sent successfully')
else:
print('It failed to send the email')
view raw smtp and email hosted with ❤ by GitHub

Python SMTPlib/Email


donation

Scan the QR code using WeChat