Python Sendmail


#! /usr/bin/env python
import smtplib
import email.Message
serv = "localhost"
sender = "test@localhost"
to = "test@gmail.com"
subject = "hello, this mail is from bigapple"
text = open("emacs.html","r").read()
def mail(serverURL=None, sender='', to='', subject='', text=''):
   
message = email.Message.Message()
   
message["To"]      = to
   
message["From"]    = sender
   
message["Subject"] = subject
   
message.set_payload(text)
     mailServer = smtplib.SMTP(serverURL)
     mailServer.set_debuglevel(1)
   
mailServer.sendmail(sender, to, message.as_string())
   
mailServer.quit()
mail(serv,sender,to,subject,text)
用户收到的时候是一个html页面, MIMEText 类型可以解决:
纯文本:
message["Content-Type"] = "text/plain"
HTML的:
message["Content-Type"] = "text/html"
               
               
                msg=MIMEMultipart()
msg['From'] = '''pppp@sina.com.cn'''
msg['To'] = '''happy@gmail.com'''
msg['Subject'] =  '''corp backup files: ''' + target_bakfile
msg['Reply-To'] = '''pppp@sina.com.cn'''
msg['Date'] = time.ctime(time.time())
msg['X-Priority'] =  '''3'''
msg['X-MSMail-Priority'] =  '''Normal'''
msg['X-Mailer'] =  '''Microsoft Outlook Express 6.00.2900.2180'''
msg['X-MimeOLE'] =  '''Produced By Microsoft MimeOLE V6.00.2900.2180'''
body=MIMEText(target,_subtype='plain',_charset='utf-8')
msg.attach(body)
fp = open(target,'rb')
ctype,encoding = mimetypes.guess_type(target)
if ctype is None or encoding is not None:
   ctype = 'application/octet-stream'
maintype,subtype = ctype.split('/',1)
m = MIMEBase(maintype,subtype)
m.set_payload(fp.read())
fp.close()
Encoders.encode_base64(m)                                             
m.add_header('Content-disposition','attachment; filename="%s"' % os.path.basename(target))
msg.attach(m)
smtpServer = smtplib.SMTP('smtp.sina.com.cn')
smtpServer.login('username','pass')
smtpServer.sendmail(msg['From'],msg['To'],msg.as_string())
smtpServer.close()