- # -*- coding: UTF-8 -*-
- '''
- 发送txt文本邮件
- '''
- import smtplib
- from email.mime.text import MIMEText
- import os, sys
- if len(sys.argv) > 5 or len(sys.argv) < 4:
- print("Usage:python %s <mail_to> [mail_cc] <mail_subject> <mail_content>" % sys.argv[0]);
- exit()
- mail_host="smtp.abc.com" #设置服务器
- mail_user="it_online" #用户名
- mail_pass="*******" #口令
- mail_postfix="abc.com" #发件箱的后缀
- mail_to=sys.argv[1]
- if len(sys.argv) > 4:
- mail_cc=sys.argv[2]
- mail_subject=sys.argv[3]
- mail_content=sys.argv[4]
- else:
- mail_subject=sys.argv[2]
- mail_content=sys.argv[3]
- def send_mail(to, cc,sub,content):
- cc=cc.strip()
- me="hello"+"<"+mail_user+"@"+mail_postfix+">"
- msg = MIMEText(content,_subtype='plain',_charset='gb2312')
- msg['Subject'] = sub
- msg['From'] = me
- msg['To'] = to
- msg['Cc'] = cc
- try:
- server = smtplib.SMTP()
- server.connect(mail_host)
- server.login(mail_user,mail_pass)
- server.sendmail(me, to, msg.as_string())
- if len(cc) <> 0:
- server.sendmail(me, cc, msg.as_string())
- server.close()
- return True
- except Exception, e:
- print str(e)
- return False
- def send_mail_nocc(to,sub,content):
- me="hello"+"<"+mail_user+"@"+mail_postfix+">"
- msg = MIMEText(content,_subtype='plain',_charset='gb2312')
- msg['Subject'] = sub
- msg['From'] = me
- msg['To'] = to
- try:
- server = smtplib.SMTP()
- server.connect(mail_host)
- server.login(mail_user,mail_pass)
- server.close()
- return True
- except Exception, e:
- print str(e)
- return False
- if __name__ == '__main__':
- if len(sys.argv) > 4:
- if send_mail(mail_to,mail_cc,mail_subject,mail_content):
- print "send sucess"
- else:
- print "send fail"
- else:
- if send_mail_nocc(mail_to,mail_subject,mail_content):
- print "send sucess"
- else:
- print "send fail"
- #该片段来自于http://www.codesnippet.cn/detail/0810201513759.html
来源: http://www.codesnippet.cn/detail/0810201513759.html