python發郵件腳本

參考菜鳥教程html

http://www.runoob.com/python/python-email.htmlpython

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Abstract: send mail

import smtplib
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
import time,sys,string


class Mail():

    def __init__(self,smtp_ip,user,pwd):
     ######第三方SMTP服務信息###
        self.smtp_host = smtp_ip
        self.user = user  ####郵件的發送方
        self.pwd = pwd
#        self.isauth = True
    def send_mail(self,mailto,subject,content):
       # print 'Setting MIMEText'
        msg = MIMEText(content,'html','utf-8')
        msg['From'] = Header(self.user,'utf-8')
        msg['Subject'] = Header(subject,'utf-8')
        msg['To'] = Header(mailto,'utf-8')
        #if self.isauth:
           # print con.docmd("EHLO %s" % self.host)
        try:
           # print 'connecting:' smtp_host   
            con = smtplib.SMTP(self.smtp_host)
            con.set_debuglevel(smtplib.SMTP.debuglevel)
            con.login(self.user,self.pwd)
            #print 'connect successfully'
            r = con.sendmail(self.user,mailto,msg.as_string())
            con.close()
            return r
        except smtplib.SMTPException,e:
            #print e
            pass


current_time = time.strftime('%Y-%m-%d %H:%M',time.localtime(time.time()))
mail = Mail('ip','mailfrom',"password")
mailto = sys.argv[1]
subject = sys.argv[2]
content = sys.argv[3]
with open('/tmp/sendmail.log','ab') as f:
        f.write('%s Receive address: %s Title: %s\n' %(current_time,mailto,subject))
mail.send_mail(mailto,subject,content)
print 'mail was sent!'
###郵件服務器無需驗證的
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
import smtplib
def send_email(msg):
    #now = datetime.datetime.now()
    #before = now-datetime.timedelta(days=1)
    content_head = "<div style=\"floatleft;font-weight:bold;\">Hi, &nbsp; all:</div><span style=\"font-weight:bold;\"> &nbsp;&nbsp;&nbsp;&nbsp 該郵件爲ship系統上線次數統計, <b:r>提示:<br> 無需回覆,持續觀察。</span><br>"
    msg_mail = content_head + msg
    def _format_addr(s):
        name, addr = parseaddr(s)
        return formataddr(( \
            Header(name, 'utf-8').encode(), \
            addr.encode('utf-8') if isinstance(addr, unicode) else addr))
    from_addr = "*"
    to_addr = "*"
    to_cc_addr = "*"
    smtp_server = "mail.com"
    msg = MIMEText(msg_mail, 'html', 'utf-8')
    msg['From'] = _format_addr(u'Momo SA <%s>' % from_addr)
    msg['To'] = to_addr
    msg['Cc'] = to_cc_addr
    msg['Subject'] = Header(u'【ship上線次數統計】', 'utf-8').encode()
    server = smtplib.SMTP(smtp_server, 25)
    server.set_debuglevel(1)
    server.sendmail(from_addr,to_addr.split(',')+to_cc_addr.split(','), msg.as_string())
    server.quit()
相關文章
相關標籤/搜索