Chinaunix

标题: 关于用python来发email,用smtplib [打印本页]

作者: bigapple2008    时间: 2006-05-15 11:40
标题: 关于用python来发email,用smtplib
毕业设计里需要用到的,代码如下:

  1.       1 #! /usr/bin/env python
  2.       2
  3.       3 import smtplib
  4.       4 import email.Message
  5.       5
  6.       6 serv = "localhost"
  7.       7 sender = "zdai@localhost"
  8.       8 to = "bigapple2008@gmail.com"
  9.       9 subject = "hello, this mail is from bigapple"
  10.      10 text = open("emacs.html","r").read()
  11.      11
  12.      12 def mail(serverURL=None, sender='', to='', subject='', text=''):
  13.      13         message = email.Message.Message()
  14.      14         message["To"]      = to
  15.      15         message["From"]    = sender
  16.      16         message["Subject"] = subject
  17.      17         message.set_payload(text)
  18.      18         mailServer = smtplib.SMTP(serverURL)
  19.      19         mailServer.set_debuglevel(1)
  20.      20         mailServer.sendmail(sender, to, message.as_string())
  21.      21         mailServer.quit()
  22.      22
  23.      23
  24.      24 mail(serv,sender,to,subject,text)
复制代码

这个是我在测试的一个函数,能正常发送。但发出去的是文本,我读入的即使是html文件,邮箱里也只能收到<html><head>。。。。等之类的文本符号。
我原来是想能让用户收到的时候是一个html页面,然后可以放点链接在信里。小弟对smtp和邮件方面不熟悉,是不是需要用到MIME之类的东西啊。
作者: ybbkd2    时间: 2006-05-16 09:14
给你参考一下,这个可以发送附件。

其中 MIMEText 类型可以解决你的问题。


[code]
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()
[/code]
作者: 星尘细雨    时间: 2006-05-17 12:37
试试加上对文本类型信息的说明:

纯文本:
message["Content-Type"] = "text/plain"
HTML的:
message["Content-Type"] = "text/html"
作者: bigapple2008    时间: 2006-05-18 09:29
赞,我用楼上的方法试了下,果然可以..
多谢啊




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2