python 发送邮件

我不但抄袭别人的博客,还抄袭别人的脚本。。。。

先安装个posfix

yum install -y  postfix 

最简单的配置

# vi /etc/postfix/main.cf
+++++++++++++++++++++++++++++
queue_directory = /var/spool/postfix
command_directory = /usr/sbin
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
mail_owner = postfix
inet_interfaces = localhost
inet_protocols = all
mydestination = $myhostname, localhost.$mydomain, localhost
unknown_local_recipient_reject_code = 550
relay_recipient_maps = hash:/etc/postfix/relay_recipients
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases


debug_peer_level = 2
debugger_command =
     PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin
     ddd $daemon_directory/$process_name $process_id & sleep 5
sendmail_path = /usr/sbin/sendmail.postfix
newaliases_path = /usr/bin/newaliases.postfix
mailq_path = /usr/bin/mailq.postfix
setgid_group = postdrop
html_directory = no
manpage_directory = /usr/share/man
sample_directory = /usr/share/doc/postfix-2.6.6/samples
readme_directory = /usr/share/doc/postfix-2.6.6/README_FILES

ok
启动 服务

systemctl start postfix

测试是否能发送

echo "Mail Content" | mail -s "Mail Subject" xxxxxxxx@qq.com

能发送。可能你在安装的时候还缺什么组件,有报错的话,就安装。简化版本的就是这样。

我想写个脚本就是工作这样:
1。能使用命令行发送。
2。能发送附件
3。也可以使用将内容填写到文件中,然后程序去读。
4。如果是数据的话,可以什么表格或者图之类的xls文件或者html文件。
5。程序可供别人调用。
++++++++++++++++++++++++++++++++++++++++++
container.py
这里有个坑,就是self.ob[“To”]是收件人,这个收件人是不是邮箱的地址,当然也可以是邮箱的地址。但是一个字符串类型,不是list类型。
这里写图片描述
上图中的to就是了。可以是asb@dafda.com,可以和收件地址无关。

[root@VM_131_54_centos diudiu]# cat container.py 
#encoding:utf-8
import os
import sys
import smtplib
import mimetypes
from optparse import OptionParser
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


class CreateEmail():

    def  __init__(self,ob=None):
        if not ob:
                    self.ob = MIMEMultipart()
        else:
            self.ob = ob
        self.debug = 1
        self.recipients = 'weare@tiantian.com' 
        self.__getallargs = {'addressor':'',
                                   "textbody":'',
                                   "others":[],
                                   "subject":None,
                                   "smtpserver":'localhost',
                   "to":[]}
        self.getallargs = self.__getallargs 
    def startsendmail(self):

                try:        

                se = smtplib.SMTP(self.__getallargs['smtpserver'])
                                self.ob['To'] = self.recipients        
                                if int(self.debug) == 1:
                                        print u"发件人:%s\n收件人:%s\n主题:%s\n"%(self.ob['From'],self.ob['To'],self.ob["Subject"])
                                        print u"开始发送--------------"

                                se.set_debuglevel(1)
                x  =self.__getallargs['to']
                se.sendmail(self.ob['From'],x, self.ob.as_string())
                                se.quit()
                if self.debug ==1:

                                        print u'发送成功\n'

                except Exception as e:
                                if self.debug ==1:
                                        print '<DEBUG:>',e
                                self.errormsg("startsendmail",e)

    #修改smtp服务器地址,以及密码
    def alterSmtpserver(self,server="localhost",username=None,passwd=None):
        #这里不用密码验证
        self.__getallargs["smtpserver"] = server



    # 修改发件人,默认是awifi_jiankong@51awifi.com 格式:a只能为字符串 如"awifi_jiankong@51awifi.com"
    def altersender(self,a):
        try:
            self.__getallargs['addressor'] = a
            self.ob['From'] = a

        except Exception as e:
            self.errormsg("altersender",e)


    #添加邮件的主题     theme:“致未来的你的一封xx”
    def addtheme(self,theme):
        self.__getallargs["subject"] = theme
        self.ob['Subject'] = theme


    #添加正文,目前只能正文只能是纯文本。
    def addTextBody(self,text=None,path=None):

        if  path and not text:
            try:

                f = open(path,'rb')
                self.__getallargs['textbody'] = f.read(4096)
                f.close()

                text_msg = MIMEText(self.__getallargs["textbody"])
                self.ob.attach(text_msg)                
            except Exception as e:
                self.errormsg("addTextBody_1",e)

        elif  not path and text:
            try:
                self.__getallargs['textbody'] = text
                text_msg = MIMEText(self.__getallargs["textbody"])
                self.ob.attach(text_msg)
            except Exception as e:
                self.errormsg("addTextBody_2",e)



    #添加收件人.1).单人可以直接“297102372@qq.com”  ; 2.)多人以及单人"297002372@qq.com,2478304062@qq.com"
    def addreceiver(self,man):
        try:
            w = man.split(",")
            self.__getallargs['to'] += w

        except Exception as e:
            self.errormsg("addreceiver",e)


    #添加附件 路径可以"/home/joker/huahua.png"或以数组的方式"     "/home/joker/huahua.png,/home/joker/yufu.png"    
    def addaccessory(self,path):
        try:
            p = path.split(",")
            self.__getallargs['others'] += p
            print p
            for f in p:
            print f
                        fp = open(f, 'rb')
                        source = MIMEApplication(fp.read())
                        source.add_header("Content-Disposition",'attachment',filename=f)
                        fp.close()
                        self.ob.attach(source)
        except Exception as e:
            self.errormsg("addaccessory",e)



    def readAllFromTextFile(self):  # -at  --alltextfile
        pass                 #也可以带上附件的路径



    #记录错误信息 
    def errormsg(self,errorwhere,e):
            try:
            ntime = os.popen("date +'%Y-%m-%d %H:%M:%S'").read()
            ntime = ' '.join(ntime.split())
            with open("error_sendmail.log",'a+') as f:              
                f.write(ntime+':'+'<'+errorwhere+'>'+'----------->'+str(e)+'<error>\n')
        except Exception as e:
                print '<debug_in_errorMsg>',e



if __name__ == "__main__":
        c = CreateEmail()
        c.addTextBody(text="        hello every one<p>zz</p>")
        c.addreceiver("297102372@qq.com,2478314062@qq.com")
        c.addaccessory("11.png,22.png")
        c.addtheme("hello")
        c.altersender("joker@hexian.cn")
        c.startsendmail()

为了命令行下能使用,使用看了下别人值怎么使用optparse模块:
用例如下:

[root@VM_131_54_centos diudiu]# python raw.py  -b "hello world"  -a 'joker@hexian.cn' \
-t '297002372@qq.com,2478304062@qq.com' -s "tomylove" -o "11.png,22.png"

raw.py如下

[root@VM_131_54_centos diudiu]# cat raw.py 
#encoding:utf-8
import os
import sys
import smtplib
import mimetypes
from optparse import OptionParser
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import copy
COMMASPACE = ','

class CreateEmail():

    def  __init__(self,ob=None):
        if not ob:
                    self.ob = MIMEMultipart()
        else:
            self.ob = ob
        self.debug = 1
        self.recipients = 'awifi@51awifi.com' 
        self.__getallargs = {'addressor':'',
                                   "textbody":'',
                                   "others":[],
                                   "subject":None,
                                   "smtpserver":'localhost',
                   "to":[]}
        self.getallargs = self.__getallargs 
    def startsendmail(self):

                try:        

                se = smtplib.SMTP(self.__getallargs['smtpserver'])
                                self.ob['To'] = self.recipients        
                                if int(self.debug) == 1:
                                        print u"发件人:%s\n收件人:%s\n主题:%s\n"%(self.ob['From'],self.ob['To'],self.ob["Subject"])
                                        print u"开始发送--------------"

                                se.set_debuglevel(1)
                x  =self.__getallargs['to']
                se.sendmail(self.ob['From'],x, self.ob.as_string())
                                se.quit()
                if self.debug ==1:

                                        print u'发送成功\n'

                except Exception as e:
                                if self.debug ==1:
                                        print '<DEBUG:>',e
                                self.errormsg("startsendmail",e)

    #修改smtp服务器地址,以及密码
    def altersmtpserver(self,server="localhost",username=None,passwd=None):
        #这里不用密码验证
        self.__getallargs["smtpserver"] = server



    # 修改发件人,默认是awifi_jiankong@51awifi.com 格式:a只能为字符串 如"awifi_jiankong@51awifi.com"
    def altersender(self,a):
        try:
            self.__getallargs['addressor'] = a
            self.ob['From'] = a

        except Exception as e:
            self.errormsg("altersender",e)


    #添加邮件的主题     theme:“致未来的你的一封xx”
    def addtheme(self,theme):
        self.__getallargs["subject"] = theme
        self.ob['Subject'] = theme


    #添加正文,目前只能正文只能是纯文本。
    def addtextbody(self,text=None,path=None):

        if  path and not text:
            try:

                f = open(path,'rb')
                self.__getallargs['textbody'] = f.read(4096)
                f.close()

                text_msg = MIMEText(self.__getallargs["textbody"])
                self.ob.attach(text_msg)                
            except Exception as e:
                self.errormsg("addTextBody_1",e)

        elif  not path and text:
            try:
                self.__getallargs['textbody'] = text
                text_msg = MIMEText(self.__getallargs["textbody"])
                self.ob.attach(text_msg)
            except Exception as e:
                self.errormsg("addTextBody_2",e)



    #添加收件人.1).单人可以直接“297002372@qq.com”  ; 2.)多人以及单人"297002372@qq.com,2478304062@qq.com"
    def addreceiver(self,man):
        try:
            w = man.split(",")
            self.__getallargs['to'] += w

        except Exception as e:
            self.errormsg("addreceiver",e)


    #添加附件 路径可以"/home/joker/huahua.png"或以数组的方式"     "/home/joker/huahua.png,/home/joker/yufu.png"    
    def addaccessory(self,path):
        try:
            p = path.split(",")
            self.__getallargs['others'] += p
            print p
            for f in p:
            print f
                        fp = open(f, 'rb')
                        source = MIMEApplication(fp.read())
                        source.add_header("Content-Disposition",'attachment',filename=f)
                        fp.close()
                        self.ob.attach(source)
        except Exception as e:
            self.errormsg("addaccessory",e)



    def readAllFromTextFile(self):  # -at  --alltextfile
        pass                 #也可以带上附件的路径



    #记录错误信息 
    def errormsg(self,errorwhere,e):
            try:
            ntime = os.popen("date +'%Y-%m-%d %H:%M:%S'").read()
            ntime = ' '.join(ntime.split())
            with open("error_sendmail.log",'a+') as f:              
                f.write(ntime+':'+'<'+errorwhere+'>'+'----------->'+str(e)+'<error>\n')
        except Exception as e:
                print '<debug_in_errorMsg>',e
    #使用命令行参数模式
    def getOptions(self):
            parser =  OptionParser()

            parser.add_option('-b','--textbody-stdin',
                      type='string', action='store',dest="ts",
                      help=u"正文,标准输入。使用方法:python mailextend.py -ts 'hello , moon'")

        parser.add_option('-f','--textbody-file',
                      type='string', action='store',dest="tf",
                      help=u"正文,以文件的形式。使用方法:python mailextend.py -F /home/joker/tt.txt")

            parser.add_option('-a', '--addressor',
                      type='string', action='store',dest="sender",
                      help=u"""发件人。使用方法:python mailextend.py  -f  joker@qq.com或  -f joker""")

            parser.add_option('-t', '--tosomeone',
                      type='string', action='store',dest="to",
                      help=u"""收件人。使用方法:python mailextend.py  -t  297002372@qq.com""")

            parser.add_option('-s', '--subject',
                      type='string', action='store',dest="subject",
                      help=u"""主题。使用方法:python mailextend.py  -s  '致未来的一份信' """)
            parser.add_option('-o', '--others',
                      type='string', action='store', dest="others",
                      help=u"""附件。使用方法:python mailextend.py  -o  '/home/joker/titi.png' """)
            parser.add_option('-d', '--debug',
                      type='string', action='store', dest="debug",
                      help=u"""打印你输入的信息。使用方法:python mailextend.py  -d 0 或 -d 1 (0为静默,1打印) """)

            (opts, args) = parser.parse_args()

        #添加正文
        if  not opts.tf  and  opts.ts:
            #print opts.tf,opts.ts
                        self.addtextbody(opts.ts,path=None)

        elif  opts.tf  and  not opts.ts:
            #print opts.tf,opts.ts
                        self.addtextbody(text=None,path=opts.tf)

        #是否显示信息
        if  opts.debug:
            self.debug = opts.debug

        #修改发件人
        if  opts.sender:
            self.altersender(opts.sender)

        #添加主题
        if  opts.subject:
            self.addtheme(opts.subject)

        #添加附件
        if  opts.others:
            self.addaccessory(opts.others)

        #添加收件人
        if  opts.to:
            self.addreceiver(opts.to)

        if  opts.to and opts.subject and ( not opts.tf or not opts.ts):
            self.startsendmail()            
        #print opts.debug

if __name__ == "__main__":
        c = CreateEmail()
        c.getOptions()

        #c.addTextBody(text="hello every one<p>zz</p>")
        #c.addreceiver("297102372@qq.com,2478304062@qq.com")
        #c.addaccessory("11.png,22.png")
        #c.addtheme("hello")
        #c.altersender("joker@zxy.cn")
        #c.startsendmail()
        #print "hi"

感觉这段时间python的水平有所进步。默默说一句这不是错觉。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值