Skip to content

Instantly share code, notes, and snippets.

@Sebastian1011
Last active November 11, 2016 13:54
Show Gist options
  • Save Sebastian1011/6467e3f18abb9cf639895f1022e86ba9 to your computer and use it in GitHub Desktop.
Save Sebastian1011/6467e3f18abb9cf639895f1022e86ba9 to your computer and use it in GitHub Desktop.
python send email
#!/usr/bin/python
# -*- coding: utf-8 -*-
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.MIMEImage import MIMEImage
import sys
import os
import re
import urllib2
import screenShot
import getpass
# mail config and image website constant
mail_host = "smtp.gmail.com"
mail_user = "yourEmail@gmail.com"
mail_pass = r"password"
mail_subtitle = getpass.getuser() + " Have New Article"
send_to_email_list = ["toEmail@gmail.com"]
screenshot_website = 'http://yt-dragonfly.tech/dragonfly/archives/'
screenshot_image = 'screenShotImg.png'
if len(sys.argv) > 1:
mail_subtitle = getpass.getuser() + "'s new article: " + sys.argv[1]
print mail_subtitle
pass
# 生成website screenshot
s = screenShot.Screenshot()
s.capture( screenshot_website, screenshot_image)
# 如名字所示Multipart就是分多个部分
msg = MIMEMultipart('related')
msg["Subject"] = mail_subtitle
msg["From"] = mail_user
msg["To"] = ";".join(send_to_email_list)
msg.preamble = mail_subtitle
#Encapsulate the plain and HTML versions of the message body in an
# 'alternative' part , so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
# ---这是文字部分---
# msgText = MIMEText('This is the alternative plain text message.')
# msg.attach(msgText)
# reference the image in the IMG SRC attribute by the ID given below
msgText = MIMEText('<a href="http://yt-dragonfly.tech/dragonfly/archives/"><br><img src="cid:image1"><br><a>', 'html', 'utf-8')
msgAlternative.attach(msgText)
# read IMG in the folder
fp = open(screenshot_image)
msgImage = MIMEImage(fp.read())
fp.close()
os.remove(screenshot_image)
# define IMG ID as referenced above
msgImage.add_header('Content-ID', '<image1>')
msg.attach(msgImage)
# ---这是附件部分---
# xls类型附件
# part = MIMEApplication(open('billing.xls', 'rb').read())
# part.add_header('Content-Disposition', 'attachment', filename="billing.xls")
# msg.attach(part)
s = smtplib.SMTP_SSL(mail_host) # 连接smtp邮件服务器,端口默认是25
s.login(mail_user, mail_pass) # 登陆服务器
s.sendmail(mail_user, send_to_email_list, msg.as_string()) # 发送邮件
s.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment