python程序发送email的源码

把开发过程经常用的代码段收藏起来,下边代码段是关于python程序发送email的的代码,应该是对码农们有一些好处。


server = ‘smtp.gmail.com:587‘;

#imports
from time import sleep;
import smtplib;
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText;
from email.mime.multipart import MIMEMultipart;

# takes addresses to, from cc and a subject
def create_msg(to_address,
               from_address=‘‘,
               cc_address=‘‘,
               bcc_address=‘‘,
               subject=‘‘):

    msg = MIMEMultipart();
    msg[‘Subject‘] = subject;
    msg[‘To‘] = to_address;
    msg[‘Cc‘] = cc_address;
    msg[‘From‘] = from_address;
    return msg;

# if mode = 0 sends to and cc
# if mode = 1 sends to bcc
def send_email(smtp_address, usr, password, msg, mode):
    server = smtplib.SMTP(smtp_address);
    server.ehlo();
    server.starttls();
    server.ehlo();
    server.login(username,password);
    if (mode == 0 and msg[‘To‘] != ‘‘):
        server.sendmail(msg[‘From‘],(msg[‘To‘]+msg[‘Cc‘]).split(","), msg.as_string());
    elif (mode == 1 and msg[‘Bcc‘] != ‘‘):
        server.sendmail(msg[‘From‘],msg[‘Bcc‘].split(","),msg.as_string());
    elif (mode != 0 and mode != 1):
        print ‘error in send mail bcc‘; print ‘email cancled‘; exit();
    server.quit();

# compose email
# takes all the details for an email and sends it
# address format: list, [0] - to
#                       [1] - cc
#                       [2] - bcc
# subject format: string
# body format: list of pairs [0] - text
#                            [1] - type:
#    0 - plain
#    1 - html
# files is list of strings
def compose_email(addresses, subject, body, files):

    # addresses
    to_address = addresses[0];
    cc_address = addresses[1];
    bcc_address = addresses[2];

    # create a message
    msg = create_msg(to_address, cc_address=cc_address , subject=subject);

    # add text
    for text in body:
        attach_text(msg, text[0], text[1]);

    # add files
    if (files != ‘‘):
        file_list = files.split(‘,‘);
        for afile in file_list:
            attach_file(msg, afile);

    # send message
    send_email(server, username, password, msg, 0);

    # check for bcc
    if (bcc_address != ‘‘):
        msg[‘Bcc‘] = bcc_address;
        send_email(server, username, password, msg, 1);

    print ‘email sent‘

# attach text
# attaches a plain text or html text to a message
def attach_text(msg, atext, mode):
    part = MIMEText(atext, get_mode(mode));
    msg.attach(part);

# util function to get mode type
def get_mode(mode):
    if (mode == 0):
        mode = ‘plain‘;
    elif (mode == 1):
        mode = ‘html‘;
    else:
        print ‘error in text kind‘; print ‘email cancled‘; exit();
    return mode;

# attach file
# takes the message and a file name and attaches the file to the message
def attach_file(msg, afile):
    part = MIMEApplication(open(afile, "rb").read());
    part.add_header(‘Content-Disposition‘, ‘attachment‘, filename=afile);
    msg.attach(part);

#to be tested...
compose_email([‘[email protected]‘,‘‘,‘‘],
              ‘test v.5.0‘,
              [[‘some text goes here...n‘,0]],
              ‘‘);

#compose_email can take the following arguments:
#   1. to recipients (separated by a comma)
#   2. cc recipients (separated by a comma)
#   3. bcc recipients (separated by a comma)
#   4. subject
#   5. a list with message and mode (plain txt or html)
#   6. files to be attached

原文地址:https://blog.51cto.com/14397541/2430364

时间: 2024-08-30 05:04:06

python程序发送email的源码的相关文章

Linux下的程序包管理之源码形式

 Linux下程序包管理之源码形式 程序包的前世今生: 说到程序包管理,不得不提到是就是程序包是由什么组成的?也就是怎么形成的?程序是由源代码程序经过预处理.编译.然后汇编形成二进制的程序,这是针对特定硬件而形成的程序.有计算机编程基础的同学都应该知道源代码编译的时候是要调用特定的库(库文件),而这些库,在不同的系统上是不同的,比如Linux和window上的就不同,不同发行版的Linux上的库也不尽相同,所以这就导致了在不同种类系统上编译生成的二进制程序的运行环境也不尽相同,那么这些程序是不能

80个Python经典资料(教程+源码+工具)汇总——下载目录 ...

原文转自:http://bbs.51cto.com/thread-935214-1.html 大家好,51CTO下载中心根据资料的热度和好评度收集了80个Python资料,分享给Python开发的同学.内容包括1个Python专题.66个学习资料.7套Python源码和6个相关软件.附件较多,无法一一分享,在此大家整理一个下载目录了,可以保存以备后用,需要时可选择性下载. 附件下载地址:http://down.51cto.com/data/432858 附件内容部分预览: [专题推荐]Pytho

VC++环境下多文档模板应用程序开发(带源码)

我们以前见到的关于VC++环境下利用APP Wizard 自动生成的MDI的应用程序只支持打开同一文档类型的多个文件,但是不能够同时打开不同种类型的文档.网上的这种公开资料比较少,我在知网上查阅了相关的资料.下面我根据这些资料做一下总结(辛辛苦苦一个一个字码出来的). 下面设计一个能够处理两种文档类型的应用程序:第一种文档类型:TXT文档,第二种文档类型:Bub的文档类型. 第一种的文档类型TXT,是利用APP Wizard自动生成的,只不过是在设置的时候将文档类型设置为TXT类型,并且使生成的

Android应用程序启动过程——Launcher源码分析

当我们在Launcher界面单击一个应用程序图标时就会启动一个程序,那这一个过程究竟发生了些哪样呢?让我们跟踪Launcher源码来分析一下吧. 先上流程图: step1.追踪Launcher  从源码中我们可以发现Launcher其实也是一个程序,它继承于Activity.找到该文件中的onCreate()方法,代码片段如下: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceSta

程序员表白系列源码

程序员表白系列源码 这里只是借花献佛 曾经也有人进行过整理 http://download.csdn.net/album/detail/1501

使用Java程序发送Email

    目前很多大型的网站忘记登录密码常见的一种形式是使用邮箱找回密码  最近做项目也有这个需求  现在总结一下  以便以后查看 使用到的包有 mailapi.jar smtp.jar   封装发送邮件的实体 package com.tes; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mai

第二篇:Python高性能Web框架tornado源码剖析之待请求阶段

上篇<第一篇:Python高性能Web框架Tornado原理剖析>用上帝视角多整个框架做了一个概述,同时也看清了web框架的的本质,下面我们从tornado程序的起始来分析其源码. 概述 上图是tornado程序启动以及接收到客户端请求后的整个过程,对于整个过程可以分为两大部分: 启动程序阶段,又称为待请求阶段(上图1.2所有系列和3.0) 接收并处理客户端请求阶段(上图3系列) 简而言之: 1.在启动程序阶段,第一步,获取配置文件然后生成url映射(即:一个url对应一个XXRequestH

linux程序包管理之源码编译安装

一.linux程序包基础概念 1.1.linux程序开发遵循开源协定:GPL, BSE, Apache等 1.2.源程序常用的开发语言:C, C++, perl, python等 1.3.应用程序的开发.编译和运行 就像面包师直接使用的材料是面粉而非麦种一样,我们大部分应用程序员在开发程序时也并非直接接触硬件层,因为底层硬件太过抽象和"丑陋",如果应用程序开发都从底层开始,无疑工作量巨大.于是,有些系统级程序员在"裸机"上抹上了一层操作系统,用于管理硬件资源,这个系

linux程序包管理与源码安装

一.RPM包简介: linux之所以那么强大,除了linux强大的内核,还有很大一部分取决于linux的软件包,假想没有软件包,就一个内核在运行,人类需要和内核打交道是多么痛苦,但是聪明的人类发明了bash,通过bash,人就可以使用高级语言,和机器沟通,这其中的bash起始也是一个软件包,当然linux除了bash还有各式各样的包,帮助我们完成各种任务,这其中便涉及到程序的包管理. rpm包管理器(原名redhat package manager,后成为行业标准,命名为rpm package