Python write automation-Email sending (anonymous), python mail sending

Source: Internet
Author: User
Tags nslookup

Python write automation-Email sending (anonymous), python mail sending

In order to realize the mail sending function, first of all, we need to know the mail sending process is what it looks like, here no longer detailed description, please search or view the http://www.sogouqa.com /? P = 438

After learning about the mail sending process, we need to use the windows command line to parse the anonymous server of the mail, and then use the anonymous server to enable automatic anonymous email sending, send an email to the corresponding email address

The Code is as follows:

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]) Destination T: ip = _ getIP (I) if ip: external (ip) if mail_exchangerIPs or name_server: print "mail_exchangers", mail_exchangerIPs return mail_exchangerIPs else: print "mail_exchangers from preconfiguration", convert (domain_name, []) return partition (domain_name, [])
Here, a function is used to obtain the address of an anonymous email server and return the value using regular expression analysis. The Code is as follows:

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

After the address is available, we need to parse the IP address. Similarly, we can use the windows Command to obtain the result and obtain the IP address through regular analysis. The Code is as follows:

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

With the IP address of the mailbox server, the rest is to use the IP address to send emails. The code is relatively simple.

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 # construct the MIMEMultipart object as the root container main_msg = email. MIMEMultipart. MIMEMultipart () # Set the root container attribute main_msg ['from'] = From main_msg ['to'] = To main_msg ['subobject'] = Subject if Date: main_msg ['date'] = Date else: main_msg ['date'] = email. utils. formatdate () # construct the MIMEText object as the mail display content and attach it to the root container text_msg = email. MIMEText. MIMEText (Body, 'html', encoding) main_msg.attach (text_msg) # construct the MIMEBase object as the file attachment content and attach it to the root container 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) failed T: 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) # send mail 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 () handle T: pass try: server. quit () failed T: pass if ret = False or ret: # print "failed to send the following email:", rcpt_toreturn False return True
OK. After the entire process is clearly organized, the email can be automatically sent.

Reprinted please indicate the source: http://blog.csdn.net/sogouauto


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.