apache_conf 如何通过Python脚本发送附带文本文件的电子邮件?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了apache_conf 如何通过Python脚本发送附带文本文件的电子邮件?相关的知识,希望对你有一定的参考价值。
#!/usr/bin/python
import smtplib
from smtplib import SMTP_SSL as SMTP
import mimetypes
import os
import datetime
import email
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import encoders
import conf
counter = 0
def send_email(conf, m):
try:
if conf.email_port == 25:
s = smtplib.SMTP(conf.email_server, conf.email_port)
elif conf.email_port == 587:
s = smtplib.SMTP(conf.email_server, conf.email_port)
s.ehlo()
s.starttls()
s.ehlo()
elif conf.email_port == 465:
s = smtplib.SMTP_SSL(conf.email_server, conf.email_port)
else:
return False
s.set_debuglevel(conf.debuglevel)
s.login(conf.from_addr, conf.passwd)
s.sendmail(conf.from_addr, conf.alert, m.as_string())
s.quit()
print 'successfully sent the email'
return True
except:
return False
# main program
for dirname, dirnames, filenames in os.walk(conf.path):
for filename0 in filenames:
if conf.pattern in filename0:
counter = 1
# email header
m = MIMEMultipart()
m['To'] = conf.to_addr
m['From'] = conf.from_addr
m['Subject'] = conf.subject_header
date = datetime.datetime.now().strftime('%d/%m/%Y %H:%M')
body = 'This is the email body. Sent on %s.' % (date)
m.attach(MIMEText(body))
# attaching text file to email body
fp = open(conf.path+'/'+filename0, 'rb')
msg = MIMEBase('multipart', 'plain')
msg.set_payload(fp.read())
fp.close()
encoders.encode_base64(msg)
msg.add_header('Content-Disposition',
'attachment', filename=filename0)
m.attach(msg)
# send email
if not send_email(conf, m):
print "failed to send email"
# delete file ?
if conf.delete_files:
os.remove(conf.path+'/'+filename0)
# better alert than do nothing ;)
if counter == 0:
# email header
m = MIMEMultipart()
m['To'] = conf.alert
m['From'] = conf.from_addr
m['Subject'] = conf.subject_alert
date = datetime.datetime.now().strftime('%d/%m/%Y %H:%M')
body = 'Error sending email attachment. Sent on %s.' % (date)
m.attach(MIMEText(body))
# send email
if not send_email(conf, m):
print "failed to send mail"
# 1 FOR TESTING PURPOSES ONLY!!!
debuglevel = 1
# file format to send
pattern = '.txt'
# files to sent path
path = 'path = ‘/path/where/files/to/send/'
# delete file after sending?
delete_files = False
# email server configuration
from_addr = 'from@XXX.XX'
passwd = 'XXXXXXXX'
email_server = 'smtp.example.com'
# email_port variable
# protocol = port number
# SMTP = 25
# SMTP with STARTTLS = 587
# SSL/TLS = SMTP-over-SSL = 465
email_port = 587
# destination email
to_addr = 'to@XXX.XX'
subject_header = 'sent'
# alert email
alert = 'to_alert@XXX.XX'
subject_alert = 'alert'
以上是关于apache_conf 如何通过Python脚本发送附带文本文件的电子邮件?的主要内容,如果未能解决你的问题,请参考以下文章
Python系列Python自动发邮件脚本
使用 argparse 将参数发送到 Python 脚本中的函数
通过python为ZABBIX发告警邮件
apache_conf [gmail SMTP info]用于配置外发电子邮件的smtp信息#gmail #smtp #notifications
python实现发工资脚本
Python发邮件的小脚本