用Python发送邮件

来源:互联网 发布:数据库储存图片路径 编辑:程序博客网 时间:2024/04/20 06:38
服务器需要周期性的检查邮件队列,然后通过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'
=====================================

转自:http://blog.csdn.net/foyuan/article/details/1709666

原创粉丝点击