[add] send mail via python, using as an alert method
This commit is contained in:
parent
b32ea0978d
commit
5efa59be75
58
alert/sendmail.py
Normal file
58
alert/sendmail.py
Normal file
@ -0,0 +1,58 @@
|
||||
#!/usr/bin/python3
|
||||
|
||||
from email.mime.text import MIMEText
|
||||
from email.mime.image import MIMEImage
|
||||
from email.mime.multipart import MIMEMultipart
|
||||
import smtplib
|
||||
import sys
|
||||
|
||||
# Mail basic information
|
||||
mail_host = "smtp.163.com"
|
||||
from_mail = 'xgdfmf@163.com'
|
||||
from_mail_password = 'SATTGHVFIJEGZMFP'
|
||||
receiver_to = ['mffan0922@163.com']
|
||||
receiver_cc = []
|
||||
to_mail = receiver_to + receiver_cc
|
||||
|
||||
|
||||
# MIMEMultipart: mixed/alternative/related
|
||||
# (1)mixed: default option, especially situation with mail attachments must use this one
|
||||
# (2)alternative: with both plain text and hyper text in mail content, using this one
|
||||
# (3)related:sending content of html format, probably using picture as the background of mail
|
||||
# content, then html text will be stored in alternative segment, whereas the background picture
|
||||
# will be stored in multipart/related segment
|
||||
|
||||
# Mail content
|
||||
msg = MIMEMultipart()
|
||||
msg['From'] = from_mail
|
||||
msg['To'] = ";".join(to_mail)
|
||||
msg['Subject'] = sys.argv[1]
|
||||
txt = sys.argv[2]
|
||||
body = MIMEText(txt, 'plain', 'utf-8')
|
||||
msg.attach(body)
|
||||
|
||||
|
||||
# Mail attachment
|
||||
if len(sys.argv) > 3:
|
||||
for attachment in sys.argv[3:]:
|
||||
filename = attachment.split('/')[-1]
|
||||
attach_file = open(attachment, 'r').read()
|
||||
attach = MIMEText(str(attach_file), 'base64', 'utf-8')
|
||||
attach["Content-Type"] = 'application/octet-stream'
|
||||
attach.add_header('Content-Disposition', 'attachment', filename=filename)
|
||||
msg.attach(attach)
|
||||
|
||||
|
||||
try:
|
||||
server = smtplib.SMTP(mail_host)
|
||||
server.docmd('helo', from_mail)
|
||||
server.starttls()
|
||||
server.login(from_mail, from_mail_password)
|
||||
|
||||
server.sendmail(from_mail, to_mail, msg.as_string())
|
||||
server.quit()
|
||||
print('sendemail successful!')
|
||||
except Exception as err:
|
||||
print('Sending email failed, the reason is as below:')
|
||||
print(err)
|
||||
|
Loading…
x
Reference in New Issue
Block a user