Python寫自動化之郵件發送(匿名)

來源:互聯網
上載者:User

標籤:郵件發送   匿名   nslookup   

為了能夠實現郵件發送功能,首先,我們需要瞭解一下郵件的發送過程是什麼樣子的,此處不再詳細說明,請大家自行搜尋或查看http://www.sogouqa.com/?p=438

在瞭解了郵件的發送過程後,為了實現郵件的全自動匿名發送,我們需要通過windows的命令列,解析郵件的匿名伺服器,然後使用匿名伺服器,發送郵件到相應的郵箱

代碼如下:

def _get_mail_exchanger(domain_name,name_server=""):    #print domain_name    temp_file=os.getenv("temp")+"\\temp.lsh"    os.system("nslookup -qt=mx "+domain_name+" "+name_server+" >"+temp_file+" 2>&1")    f=open(temp_file)    c=f.read()    f.close()    os.remove(temp_file)    #print c    internet_addresses_map=_get_internet_address(c)    mail_exchangers=re.findall(r"mail\s+exchanger\s*=\s*(\S+)",c)    #mail_exchangers=[internet_addresses_map.get(i,i) for i in mail_exchangers]    mail_exchangerIPs=[]    for i in mail_exchangers:        try:            mail_exchangerIPs.append(internet_addresses_map[i])        except:            ip=_getIP(i)            if ip:                mail_exchangerIPs.append(ip)            if mail_exchangerIPs or name_server:        print "mail_exchangers",mail_exchangerIPs        return mail_exchangerIPs    else:        print "mail_exchangers from 預配置",g_mail_exchanger.get(domain_name,[])        return g_mail_exchanger.get(domain_name,[])
其中有個函數用於擷取匿名郵箱伺服器位址,使用正則分析返回值,代碼如下:

def _get_internet_address(content):    internet_addresses=re.findall(r"(\S+)\s+internet\s+address\s*=\s*(\S+)",content)    internet_addresses_map={}    for internet_address in internet_addresses:        internet_addresses_map[internet_address[0]]=internet_address[1]    return internet_addresses_map

然後,有了地址後,我們需要通過解析出地址的IP,同樣,使用windows命令擷取結果並正則分析擷取IP,代碼如下:

def _getIP(domain_name,name_server=""):    temp_file=os.getenv("temp")+"\\temp.lsh"    os.system("nslookup -qt=a "+domain_name+" "+name_server+" >"+temp_file+" 2>&1")    f=open(temp_file)    c=f.read()    f.close()    os.remove(temp_file)    ips=re.findall(domain_name+r"\s*Address\s*:\s*(\S+)",c,re.I)        if ips:        return ips[0][0]    elif name_server=="":        return _getIP(domain_name,"8.8.8.8")    else:        return None

有了郵箱伺服器的IP,剩下的事情就是使用IP去發送郵件了,代碼比較簡單

def _send_to_mail_exchanger(mail_exchanger,mail_from,rcpt_to,From="",To="",Subject="",Date=None,Body="",attachments=None,encoding="gbk"):    import smtplib,email    from email.MIMEMultipart import MIMEMultipart    from email.MIMEText import MIMEText    from email.MIMEImage import MIMEImage    # 構造MIMEMultipart對象做為根容器    main_msg=email.MIMEMultipart.MIMEMultipart()    # 設定根容器屬性    main_msg['From'] = From    main_msg['To'] = To    main_msg['Subject'] = Subject    if Date:main_msg['Date'] = Date    else:main_msg['Date'] = email.Utils.formatdate()        # 構造MIMEText對象做為郵件顯示內容並附加到根容器        text_msg = email.MIMEText.MIMEText(Body,'html', encoding)    main_msg.attach(text_msg)    # 構造MIMEBase對象做為檔案附件內容並附加到根容器      if attachments:for attachment in attachments:        if not os.path.isfile(attachment):continue    if IsImage(attachment):try:    fp = open(attachment, "rb")    file_msg = MIMEImage(fp.read())    fp.close()    file_msg.add_header("Content-ID", os.path.basename(attachment).replace(".jpg", "").replace(".png", ""))    main_msg.attach(file_msg)except:    pass    else:file_msg=email.MIMEBase.MIMEBase("application","octet-stream")f=open(attachment,'rb')file_msg.set_payload(f.read())f.close()email.Encoders.encode_base64(file_msg)file_msg.add_header('Content-Disposition','attachment',filename=os.path.basename(attachment))main_msg.attach(file_msg)        # 用smtp發送郵件    data=main_msg.as_string()    for i in range(2):try:    Log(mail_exchanger)    server=smtplib.SMTP(mail_exchanger)    Log(mail_from)    Log(rcpt_to)    ret=server.sendmail(mail_from,rcpt_to,data)    breakexcept:    import traceback    Log(traceback.format_exc())        ret=False    try:server.quit()    except:pass    try:server.quit()    except:pass        if ret==False or ret:#print "發往如下的郵件失敗:",rcpt_toreturn False    return True
ok,這樣把整個流程整理清楚後,就可以自動發送郵件了

轉載請註明出處:http://blog.csdn.net/sogouauto


Python寫自動化之郵件發送(匿名)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.