python发邮件实例

#!/usr/bin/python
#coding=utf-8
import smtplib, mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage


msg = MIMEMultipart()
msg['From'] = "[email protected]"
msg['To'] = '[email protected]'
msg['Subject'] = 'email for tesing'


#添加邮件内容
txt = MIMEText("邮件内容!!!")
msg.attach(txt)


#添加二进制附件
fileName = r'/root/vhost.sh'
ctype, encoding = mimetypes.guess_type(fileName)
if ctype is None or encoding is not None:
    ctype = 'application/octet-stream'
maintype, subtype = ctype.split('/', 1)
att1 = MIMEImage((lambda f: (f.read(), f.close()))(open(fileName, 'rb'))[0], _subtype = subtype)
att1.add_header('Content-Disposition', 'attachment', filename = fileName)
msg.attach(att1)


#发送邮件
smtp = smtplib.SMTP()
smtp.connect("smtp.qq.com", "25")
smtp.login('[email protected]', '******')
smtp.sendmail('[email protected]', '[email protected]', msg.as_string())
smtp.quit()
print '邮件发送成功'

~                              

这是python脚本,命名为 test01.py

chmod +x test01.py

./test01.py 执行


你可能感兴趣的:(linux,python)