Skip to content

Instantly share code, notes, and snippets.

@zclongpop123
Last active September 11, 2019 06:49
Show Gist options
  • Save zclongpop123/04f4c97f58383490782eaee3edfd90f9 to your computer and use it in GitHub Desktop.
Save zclongpop123/04f4c97f58383490782eaee3edfd90f9 to your computer and use it in GitHub Desktop.
Python发送邮件
# coding: utf-8
#========================================
# author: Changlong.Zang
# mail: zclongpop123@163.com
# time: Tue Sep 10 17:56:28 2019
#========================================
import glob, random
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
#--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
def send_mail():
'''
'''
mail_host='smtp.exmail.qq.com'
mail_user='username@mailserver.com'
mail_pass='password'
sender = 'username@mailserver.com'
receivers = ['my_email@qq.com']
message = MIMEMultipart('mixed')
message['From'] = Header(u'发件人Title', 'utf-8')
message['To'] = Header(u'收件人Title', 'utf-8')
message['Subject'] = Header(u'邮件主题','utf-8')
text_message = 'text message...'
message.attach(MIMEText('{0} <p><img src="cid:image1" width="50%" height="50%"></p>'.format(text_message), 'html', 'utf-8'))
image_path = random.choice(glob.glob('/root/images/*.jpg'))
with open(image_path, 'rb') as f:
image = MIMEImage(f.read(), 'html')
image.add_header('Content-ID','<image1>')
message.attach(image)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print u'邮件发送成功'
except smtplib.SMTPException:
print u'Error: 无法发送邮件'
if __name__ == '__main__':
send_mail()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment