专栏首页python3python程序发送email的源码

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(['cpt@thelivingpearl.com','',''],
              '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

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Django之中间件

    中间件是一个用来处理Django的请求和响应的框架级别的钩子。它是一个轻量、低级别的插件系统,用于在全局范围内改变Django的输入和输出。每个中间件组件都负责...

    py3study
  • python 日志模块工具类

    py3study
  • Cent OS7安装Python 2.7

        这种安装方式为在系统原基础上进行编译安装python2.7.15不废话,直接开始主题。

    py3study
  • 蛋白质组学第4期 文章搜库过程复现

    上周我们公布了,蛋白质组学习小组起飞啦! 短短几天就获得了250多小伙伴的支持,让我们也更有信心的带领大家掌握一个蛋白质组学数据处理的实战,前面两期我们分享的...

    生信技能树
  • 吴恩达被diss了

    量子位
  • windows.onload()与$(document).ready()的区别

    在jquery中,则使用$(document).ready()方法。下面介绍一下两者的区别。

    山河木马
  • 腾讯云备案流程(领取腾讯云优惠券)

    现在很多人会用云服务器,而且现在都是要备案的,今天这里给大家整理了腾讯云的备案流程

    主机优惠教程
  • 神经网络算法

    20 世纪五、六⼗年代,科学家 Frank Rosenblatt其受到 Warren McCulloch 和 Walter Pitts早期的⼯作的影响,发明了感...

    foochane
  • icp备案和域名备案 转

    域名备案是指强大的Z-F为了监管互联网站点创新发明出的一个做法。简单地说就是把网站站长的个人或单位的真实资料,包括身份证复印件、填写网站登记表等等资料提交给你的...

    wuweixiang
  • 03-保存

    存储所需内容 ctrl+c ctrl+n ctrl+v 或者直接拖动文件至新文件

    河湾欢儿

扫码关注云+社区

领取腾讯云代金券