Chinaunix首页 | 论坛 | 博客
  • 博客访问: 467659
  • 博文数量: 65
  • 博客积分: 2645
  • 博客等级: 少校
  • 技术积分: 675
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-08 17:04
文章分类

全部博文(65)

文章存档

2010年(5)

2009年(5)

2008年(14)

2007年(35)

2006年(6)

分类: Python/Ruby

2007-07-30 19:22:41

服务器需要周期性的检查邮件队列,然后通过smtp服务器发送出去,就网上搜了搜,然后修改了加工了一下,写了一个邮件发送的简单模块

两个文件
 config.py:配置信息
 send_msg.py:发送邮件
send_msg.py
#coding=utf-8

import smtplib,config,email,sys
from email.Message import Message

def connect():
    
"connect to smtp server and return a smtplib.SMTP instance object"
    server
=smtplib.SMTP(config.smtpserver,config.smtpport)
    server.ehlo()
    server.login(config.smtpuser,config.smtppass)
    
return server
    
def sendmessage(server,to,subj,content):
    
"using server send a email"
    msg 
= Message()
    msg[
'Mime-Version']='1.0'
    msg[
'From']    = config.smtpuser
    msg[
'To']      = to
    msg[
'Subject'= subj
    msg[
'Date']    = email.Utils.formatdate()          # curr datetime, rfc2822
    msg.set_payload(content)
    
try:    
        failed 
= server.sendmail(config.smtpuser,to,str(msg))   # may also raise exc
    except Exception ,ex:
   
    print Exception,ex
        
print 'Error - send failed'
    
else:
   
    print "send success!"

if __name__=="__main__":
    
#frm=raw_input('From? ').strip()
    to=raw_input('To? ').strip()
    subj
=raw_input('Subj? ').strip()   
    
print 'Type message text, end with line="."'
    text 
= ''
    
while True:
        line 
= sys.stdin.readline()
        
if line == '. 'break
        text 
+= line
    server
=connect()
    sendmessage(server,to,subj,text)

config.py
=====================================
smtpserver='mail.xxxx.net'
smtpuser='user@xxx.net'
smtppass='pwd'
smtpport='25'
=====================================
阅读(2044) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~