代码内容如下,斜体根据自身情况修改
# -*- coding: utf-8 -*-
import smtplibfrom email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import utils
from email import encoders
import os
def sendMail(to, subject, text, files=[],server=" localhost "):
COMMASPACE = ', '
assert type(to)==list
assert type(files)==list
fro = " Liu Bin <liubin@gmail.com> "
msg = MIMEMultipart()
msg['From'] = fro
msg['To'] = COMMASPACE.join(to)
msg['Date'] = utils.formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.login( username,password )
smtp.sendmail(fro, to, msg.as_string() )
smtp.close()
if __name__=="__main__":
sendMail(
[" liubin@gmail.com "],
"hello","cheers",
[r"C:\hudson\workspace\UpdateAndBuildConsignment\script\sendEmail.py",r"D:\work_liubin\dlAnalysis.ndproj"]
)
上面的版本对中文支持有问题,如果要支持中文,首先代码格式以utf-8格式编码,再此改成如下编码:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import utils
from email import encoders
from email.header import Header
import os
def sendMail(to, subject, text, files=[],server="localhost"):
COMMASPACE = ', '
assert type(to)==list
assert type(files)==list
fro = "Liu Bin <liubin@gmail.com>"
msg = MIMEMultipart()
msg['From'] = fro
msg['To'] = COMMASPACE.join(to)
msg['Date'] = utils.formatdate(localtime=True)
msg['Subject'] = Header(subject, "utf-8")
msg.attach(MIMEText(text,"plain","utf-8"))
for file in files:
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
smtp = smtplib.SMTP(server)
smtp.login(username,password)
smtp.sendmail(fro, to, msg.as_string() )
smtp.close()
参考
http://axiii.blog.51cto.com/396236/301199
http://stackoverflow.com/questions/1966073/how-do-i-send-attachments-using-smtp
附http://blog.csdn.net/betry/article/details/6657429原文
- #-*- encoding: utf-8 -*-
- #导入smtplib和MIMEText
- import smtplib
- from