#-*-coding:utf-8-*-
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email import encoders
import smtplib
import os,datetime
time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
time_path = datetime.datetime.now().strftime('%Y-%m-%d')
# 发送邮件
def send_mail(server, fro, to, subject, htmlText, files=[]):
try:
msg = MIMEMultipart()
msg['From'] = fro
msg['Subject'] = subject
msg['To'] = COMMASPACE.join(to) # COMMASPACE==', '
msg['Date'] = formatdate(localtime=True)
# 'alternative' part, so message agents can decide which they want to display.
msgAlternative = MIMEMultipart('alternative')
msg.attach(msgAlternative)
msgText = MIMEText(htmlText, 'html', 'utf-8')
msgAlternative.attach(msgText)
for f in files:
part = MIMEBase('application', 'octet-stream') # 'octet-stream': binary data
part.set_payload(open(f, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
msg.attach(part)
smtp = smtplib.SMTP(server['name'], server['port'])
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(server['user'], server['passwd'])
smtp.sendmail(fro, to, msg.as_string())
smtp.close()
return True
except Exception as e:
print repr(e)
return False
def export_html():
htmlText = '''
<p>您好,<br/>
内容(请见附件)
</p>
'''
htmlText += 'from who' + '<br/><br/>'
htmlText += 'Have a good day!'
return htmlText
# 绝对路径 file_path = os.getcwd() + r"\\2018-03-13.xls"
# 上一级os.path.join(os.path.dirname("__file__"), os.path.pardir) 再上一级就加os.path.pardir:os.path.join(os.path.dirname("__file__"), os.path.pardir,os.path.pardir)
file_path = os.path.abspath(os.path.join(os.path.dirname("__file__"))) + r"\execl\%s.xls" %time_path
# print file_path
text = export_html()
#发送人邮箱
fro = 'xxxx@qq.com'
#收件人邮箱和抄送
# to = ['xxx@qq.com','xxxx@163.com']
to = ['xxxx@.com.cn']
邮件主题
subject = u'xxxxxxxxxxxx.'
mailserver_conf={'name':'发件人名称',
'user':'用户名账号',
'passwd':'密码',
'port':端口号,
}
send_mail(mailserver_conf,fro,to,subject,text,files=[file_path])
print '发送成功'
Python发送邮件(带附件)
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 之前写过用标准库使用Python Smtplib 和email发送邮件,感觉很繁琐,久了不用之后便忘记了。前几天看...