• Python通用发送邮件模块


    博客已迁移,文章新地址 

    ===========================

    需求:

    1.发送邮件

    2.不需要登录任何邮箱等等

    3.支持多接收人

    4.支持附件

    5.支持命令行+方法调用


    涉及模块:

    smtplib,  email


    基于版本:

    2.4

    使用2.7和3.x的童鞋,需要修改下import信息


    源代码:

    #!/usr/bin/env python
    #@author : wklken@yeah.ent
    #@version : 0.1
    #@desc: for mail sending.
    
    import smtplib
    import getopt
    import sys
    import os
    
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEBase import MIMEBase
    
    from email.MIMEText import MIMEText
    import email.Encoders as encoders
    
    
    def send_mail(mail_from, mail_to, subject, msg_txt, files=[]):
        # Create message container - the correct MIME type is multipart/alternative.
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = mail_from
        msg['To'] = mail_to
    
        # Create the body of the message (a plain-text and an HTML version).
        #text = msg
        html = msg_txt
    
        # Record the MIME types of both parts - text/plain and text/html.
        #part1 = MIMEText(text, 'plain')
        part2 = MIMEText(html, 'html')
    
        # Attach parts into message container.
        # According to RFC 2046, the last part of a multipart message, in this case
        # the HTML message, is best and preferred.
        #msg.attach(part1)
        msg.attach(part2)
    
        #attachment
        for f in files:
            #octet-stream:binary data
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(open(f, 'rb').read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
            msg.attach(part)
        # Send the message via local SMTP server.
        s = smtplib.SMTP('localhost')
        # sendmail function takes 3 arguments: sender's address, recipient's address
        # and message to send - here it is sent as one string.
    
        mailto_list = mail_to.strip().split(",")
        if len(mailto_list) > 1:
            for mailtoi in mailto_list:
                s.sendmail(mail_from, mailtoi.strip(), msg.as_string())
        else:
            s.sendmail(mail_from, mail_to, msg.as_string())
    
        s.quit()
        return True
    
    
    def main():
        files = []
        try:
            opts, args = getopt.getopt(sys.argv[1:], "f:t:s:m:a:")
            #print sys.argv
            for op, value in opts:
                if op == "-f":
                    mail_from = value
                elif op == "-t":
                    mail_to = value
                elif op == "-s":
                    subject = value
                elif op == "-m":
                    msg_txt = value
                elif op == "-a":
                    files = value.split(",")
        except getopt.GetoptError:
            print(sys.argv[0] + " : params are not defined well!")
    
        print mail_from, mail_to, subject, msg_txt
        if files:
            send_mail(mail_from, mail_to, subject, msg_txt, files)
        else:
            send_mail(mail_from, mail_to, subject, msg_txt)
    
    
    if __name__ == "__main__":
        main()
    



    The end!

    转载请注明出处,Thx!


    wklken

    Blog:  http://wklken.me

    Email: wklken@yeah.net

    2012-09-02


    Meet so Meet. C plusplus I-PLUS....
  • 相关阅读:
    记Java程序Log4J漏洞的解决过程
    IIS中应用程序池自动停止,重启报错
    如何查看域名所对应的证书有效期?
    查看前端Vue版本命令
    WCF中常见的报错:The content type text
    dotnet 将自动代码格式化机器人带入团队 GitLab 平台
    WPF 引用第三方库的控件在设计器加上设计时数据和属性
    dotnet OpenXML 聊聊文本段落对齐方式
    WPF 布局 在有限空间内让两个元素尽可能撑开的例子
    dotnet 通过 DockerfileContext 解决项目放在里层文件夹导致 VisualStudio 构建失败
  • 原文地址:https://www.cnblogs.com/iplus/p/4464626.html
Copyright © 2020-2023  润新知