精华内容
下载资源
问答
  • 该源码是针对特定网站,不是通用代码,但是具有一定的参考性,不想下载可以看我博客有相应的每个部分的代码块 http://blog.csdn.net/henni_719/article/details/60580815
  • /usr/bin/pythonfrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartfrom email.MIMEBase import MIMEBasefrom email import Utils, Encodersimport mimetypes, sys,smtplib,socke.....

    #!/usr/bin/python

    from email.MIMEText import MIMEText

    from email.MIMEMultipart import MIMEMultipart

    from email.MIMEBase import MIMEBase

    from email import Utils, Encoders

    import mimetypes, sys,smtplib,socket,getopt

    class SendMail:

    def __init__(self,smtp_server,from_addr,to_addr,user,passwd):

    self.mailserver=smtp_server

    self.from_addr=from_addr

    self.to_addr=to_addr

    self.username=user

    self.password=passwd

    def attachment(self,filename):

    fd=open(filename,'rb')

    filename=filename.split('/')

    mimetype,mimeencoding=mimetypes.guess_type(filename[-1])

    if (mimeencoding is None) or (mimetype is None):

    mimetype='application/octet-stream'

    maintype,subtype=mimetype.split('/')

    if maintype=='text':

    retval=MIMEText(fd.read(), _subtype=subtype, _charset='utf-8')

    else:

    retval=MIMEBase(maintype,subtype)

    retval.set_payload(fd.read())

    Encoders.encode_base64(retval)

    retval.add_header('Content-Disposition','attachment',filename=filename[-1])

    fd.close()

    return retval

    def msginfo(self,msg,subject,filename):

    # message = """Hello, ALL

    #This is test message.

    #--Anonymous"""

    message=msg

    msg=MIMEMultipart()

    msg['To'] = self.to_addr

    msg['From'] = 'sa '

    msg['Date'] = Utils.formatdate(localtime=1)

    msg['Message-ID'] = Utils.make_msgid()

    if subject:

    msg['Subject'] = subject

    if message:

    body=MIMEText(message,_subtype='plain')

    msg.attach(body)

    #for filename in sys.argv[1:]:

    if filename:

    msg.attach(self.attachment(filename))

    return msg.as_string()

    def send(self,msg=None,subject=None,filename=None):

    try:

    s=smtplib.SMTP(self.mailserver)

    try:

    s.login(self.username,self.password)

    except smtplib.SMTPException,e:

    print "Authentication failed:",e

    sys.exit(1)

    s.sendmail(self.from_addr,self.to_addr.split(','),self.msginfo(msg,subject,filename))

    except (socket.gaierror,socket.error,socket.herror,smtplib.SMTPException),e:

    print "*** Your message may not have been sent!"

    print e

    sys.exit(2)

    else:

    print "Message successfully sent to %d recipient(s)" %len(self.to_addr)

    if __name__=='__main__':

    def usage():

    print """Useage:%s [-h] -s -f -t -u -p [-S -m -F ]

    Mandatory arguments to long options are mandatory for short options too.

    -f, --from= Sets the name of the "from" person (i.e., the envelope sender of the mail).

    -t, --to= Addressee's address. -t "[email protected],[email protected]".

    -u, --user= Login SMTP server username.

    -p, --pass= Login SMTP server password.

    -S, --subject= Mail subject.

    -m, --msg= Mail message.-m "msg, ......."

    -F, --file= Attachment file name.

    -h, --help Help documen.

    """ %sys.argv[0]

    sys.exit(3)

    try:

    options,args=getopt.getopt(sys.argv[1:],"hs:f:t:u:p:S:m:F:","--help --server= --from= --to= --user= --pass= --subject= --msg= --file=",)

    except getopt.GetoptError:

    usage()

    sys.exit(3)

    server=None

    from_addr=None

    to_addr=None

    username=None

    password=None

    subject=None

    filename=None

    msg=None

    for name,value in options:

    if name in ("-h","--help"):

    usage()

    if name in ("-s","--server"):

    server=value

    if name in ("-f","--from"):

    from_addr=value

    if name in ("-t","--to"):

    to_addr=value

    if name in ("-u","--user"):

    username=value

    if name in ("-p","--pass"):

    password=value

    if name in ("-S","--subject"):

    subject=value

    if name in ("-m","--msg"):

    msg=value

    if name in ("-F","--file"):

    filename=value

    if server and from_addr and to_addr and username and password:

    test=SendMail(server,from_addr,to_addr,username,password)

    test.send(msg,subject,filename)

    else:

    usage()

    展开全文
  • python3自动发送邮件添加附件

    千次阅读 热门讨论 2019-09-25 00:50:29
    将本地报表文件以附件形式添加邮件发送 设置定时任务 代码 import pymysql import pandas as pd import smtplib from email.header import Header from email.mime.text import MIMEText from email.m...

    思路

    1. 从数据库读取报表数据
    2. 将报表数据以excel形式存到本地
    3. 将本地报表文件以附件形式添加到邮件发送
    4. 设置定时任务

    代码 

    import pymysql
    import pandas as pd
    import smtplib
    from email.header import Header
    from email.mime.text import MIMEText
    from email.mime.image import MIMEImage
    from email.mime.multipart import MIMEMultipart
    from email.mime.application import MIMEApplication 
    import datetime
    import schedule,time
    
    def create_report(host,port,user,passwd,db,sql,annex_path):
        '从数据库读取报表数据,以excel形式将报表存到本地'
        conn = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)# 连接mysql
        cursor = conn.cursor()#创建游标
        cursor.execute(sql)#执行sql语句
        result = cursor.fetchall()#获取执行结果    
        result=[list(x) for x in result]
        col_result = cursor.description  # 获取查询结果的字段描述
        columns=[x[0] for x in col_result]
        data=pd.DataFrame(result,columns=columns)
        data.to_excel(annex_path,index=False)
        cursor.close()#关闭游标
        conn.close()#关闭连接
    
    def send_email(file_name,annex_path):
        '#创建报表和发送邮件'  
        try:
            file_name_new=str(datetime.datetime.now().date())+file_name#根据当前日期拼接附件名称
            annex_path_new=annex_path+'/'+file_name_new  #拼接报表存储完整路径 
            create_report(host,port,user,passwd,db,sql,annex_path_new)#创建报表
            
            #传入邮件发送者、接受者、抄送者邮箱以及主题    
            message = MIMEMultipart()
            message['From'] = sender
            message['To'] = ','.join(receiver)
            message['Cc'] = ";".join(Cc_receiver)
            message['Subject'] = Header(str(datetime.datetime.now().date())+title, 'utf-8')
            
            #添加邮件内容
            text_content = MIMEText(content)
            message.attach(text_content)
            
            #添加附件    
            annex = MIMEApplication(open(annex_path_new, 'rb').read()) #打开附件
            annex.add_header('Content-Disposition', 'attachment', filename=file_name_new)   
            message.attach(annex)
    
            #image_path = 'C:/Users/yang/Desktop/1.png'
            #image = MIMEImage(open(image_path , 'rb').read(), imageFile.split('.')[-1])
            #image.add_header('Content-Disposition', 'attachment', filename=image_path.split('/')[-1])
            #message.attach(image)
            
            #登入邮箱发送报表
            server = smtplib.SMTP(smtp_ip)#端口默认是25,所以不用指定
            server.login(sender,password)
            server.sendmail(sender, receiver, message.as_string())
            server.quit()
            print('success!',datetime.datetime.now())
            
        except smtplib.SMTPException as e:
            print('error:',e,datetime.datetime.now()) #打印错误
                
    if __name__ == '__main__':
    #参数设置
        #数据库参数设置
        host='localhost'#数据库ip地址
        port=3306#端口
        user='root'#账户
        passwd='XXX'#密码
        db='XXX'#数据库名称
        sql="SELECT cid,max(score) as max_score FROM sc group by cid;"#报表查询语句
        
        #发送邮件参数设置   
        sender = 'XXX@126.com'#发送者邮箱
        password = 'XXX'#发送者邮箱授权码
        smtp_ip='smtp.126.com'#smtp服务器ip,根据发送者邮箱而定
        receiver = ['XXX@qq.com','XXX@qq.com']#接收者邮箱 
        Cc_receiver=['XXX@qq.com','XXX@126.com']#抄送者邮箱
        title='订单日报'#邮件主题
        content = 'hello,这是今天的订单日报!'#邮件内容
        file_name='订单日报.xlsx'#报表名称
        annex_path='C:/Users/yang/Desktop/'#报表存储路径,也是附件路径
        ts='10:13'#发送邮件的定时设置,每天ts时刻运行
        
    #自动创建报表并发送邮件
        print('邮件定时发送任务启动中.......')
        schedule.every().day.at(ts).do(send_email, file_name,annex_path) # 每天某时刻运行   
        while True:
            schedule.run_pending() # 运行所有可运行的任务
            time.sleep(43200)#因为每次发送邮件的间隔时间是一天左右,所以休眠时间可以设长些

    结果 

     

    授权码的获取

    其中邮箱的授权码不是邮箱的密码,而是邮箱授权给第三方软件登陆邮箱的授权。以QQ邮箱为例,获取授权码步骤如下:

    (1)登陆邮箱,点开设置:

    (2)选择账户,找到开启SMTP,点击开启:

     

    (3)点击开启后,需要本人身份验证:

    (4)验证成功后,会出现授权码:

    这个授权码,就是要在连接邮件的时候填上。

     附:常用SMTP和POP服务器地址

       1、QQ邮箱(mail.qq.com)
        POP3服务器地址:pop.qq.com(端口:110)
        SMTP服务器地址:smtp.qq.com(端口:25)
        
        2、搜狐邮箱(sohu.com):
        POP3服务器地址:pop3.sohu.com(端口:110)
        SMTP服务器地址:smtp.sohu.com(端口:25)
        
        3、HotMail邮箱(hotmail.com):
        POP3服务器地址:pop.live.com(端口:995)
        SMTP服务器地址:smtp.live.com(端口:587)
        
        4、移动139邮箱:
        POP3服务器地址:POP.139.com(端口:110)
        SMTP服务器地址:SMTP.139.com(端口:25)
        
        5、景安网络邮箱:
        POP3服务器地址:POP.zzidc.com(端口:110)
        SMTP服务器地址:SMTP.zzidc.com(端口:25)
        
        6、新浪邮箱
        smtp.sina.com(端口:25)
        
        7、新浪VIP
        SMTP服务器地址:smtp.vip.sina.com(端口:25)
        
        8、126邮箱
        SMTP服务器地址:smtp.126.com(端口:25)
        
        9、139邮箱
        SMTP服务器地址:smtp.139.com(端口:25)
        
        10、163网易邮箱
        SMTP服务器地址:smtp.163.com(端口:25) 
     

    如果对你有帮助,请点下赞,予人玫瑰手有余香!

    时时仰望天空,理想就会离现实越来越近!

    展开全文
  • 主要为大家详细介绍了Python3实现带附件的定时发送邮件功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • How do i add a document attachment when sending an email with python ?i get the email to send(please ignore: i am looping the email to send every 5 seconds, only for testing purposes, i want it to sen...

    How do i add a document attachment when sending an email with python ?

    i get the email to send

    (please ignore: i am looping the email to send every 5 seconds, only for testing purposes, i want it to send every 30 min, just have to change 5 to 1800)

    here is my code so far. how do i attach a document from my computer?

    #!/usr/bin/python

    import time

    import smtplib

    while True:

    TO = 'xxxx@gmail.com'

    SUBJECT = 'Python Email'

    TEXT = 'Here is the message'

    gmail_sender = 'xxxx@gmail.com'

    gmail_passwd = 'xxxx'

    server = smtplib.SMTP('smtp.gmail.com',587)

    server.ehlo()

    server.starttls()

    server.ehlo()

    server.login(gmail_sender, gmail_passwd)

    BODY = '\n'.join([

    'To: %s' % TO,

    'From: %s' % gmail_sender,

    'Subject:%s' % SUBJECT,

    '',

    TEXT

    ])

    try:

    server.sendmail(gmail_sender,[TO], BODY)

    print 'email sent'

    except:

    print 'error sending mail'

    time.sleep(5)

    server.quit()

    解决方案

    This is the code that worked for me- to send an email with an attachment in python

    #!/usr/bin/python

    import smtplib,ssl

    from email.mime.multipart import MIMEMultipart

    from email.mime.base import MIMEBase

    from email.mime.text import MIMEText

    from email.utils import formatdate

    from email import encoders

    def send_mail(send_from,send_to,subject,text,files,server,port,username='',password='',isTls=True):

    msg = MIMEMultipart()

    msg['From'] = send_from

    msg['To'] = send_to

    msg['Date'] = formatdate(localtime = True)

    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    part = MIMEBase('application', "octet-stream")

    part.set_payload(open("WorkBook3.xlsx", "rb").read())

    encoders.encode_base64(part)

    part.add_header('Content-Disposition', 'attachment; filename="WorkBook3.xlsx"')

    msg.attach(part)

    #context = ssl.SSLContext(ssl.PROTOCOL_SSLv3)

    #SSL connection only working on Python 3+

    smtp = smtplib.SMTP(server, port)

    if isTls:

    smtp.starttls()

    smtp.login(username,password)

    smtp.sendmail(send_from, send_to, msg.as_string())

    smtp.quit()

    展开全文
  • 之前老王介绍过《PHP 使用 SMTP 发送邮件教程(PEAR Mail 包)》,这次需求是用 Python 调用 SMTP 服务发送邮件,并且需要在邮件添加附件(文本文件),本文分享下具体的代码。一、准备工作1、SMTP 邮箱2、添加包依赖...

    之前老王介绍过《PHP 使用 SMTP 发送邮件教程(PEAR Mail 包)》,这次需求是用 Python 调用 SMTP 服务发送邮件,并且需要在邮件中添加附件(文本文件),本文分享下具体的代码。

    一、准备工作

    1、SMTP 邮箱

    2、添加包依赖

    主要用到了 2 个 Python 自带的包,其中 smtplib 就是 Python SMTP 功能必用包:

    import smtplib

    from email.mime.text import MIMEText

    二、源码分享

    以下代码就是 Python3 调用 QQ 邮箱的 SMTP 发送邮件的源码,在发送的邮件内容中添加了一个附件:

    def send_email(content, attach_file):

    msg_from = '8888888@qq.com' # 发送方邮箱

    passwd = 'tjvoskdjsklkcaij' # 填入发送方邮箱的授权码

    msg_to = '888888@gmail.com' # 收件人邮箱

    subject = "The Subject"

    msg = MIMEMultipart()

    msg.attach(MIMEText(content, 'plain', 'utf-8'))

    msg['Subject'] = subject

    msg['From'] = msg_from

    msg['To'] = msg_to

    # 构造附件1,传送当前目录下的 attach_file 文件

    att1 = MIMEText(open(attach_file, 'rb').read(), 'base64', 'utf-8')

    att1["Content-Type"] = 'application/octet-stream'

    # 这里的 filename 可以任意写,写什么名字,邮件中显示什么名字

    att1["Content-Disposition"] = 'attachment; filename="diff.html"'

    msg.attach(att1)

    try:

    s = smtplib.SMTP_SSL("smtp.qq.com", 465) # 邮件服务器及端口号

    s.login(msg_from, passwd)

    s.sendmail(msg_from, msg_to, msg.as_string())

    except Exception as e:

    print(str(e))

    展开全文
  • 主要为大家详细介绍了python实现发送邮件附件功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • 主要介绍了python 实现的发送邮件模板,包含Python发送普通邮件、带附件及带图片邮件相关实现技巧,需要的朋友可以参考下
  • How do i add a document attachment when sending an email with python ?i get the email to send(please ignore: i am looping the email to send every 5 seconds, only for testing purposes, i want it to sen...
  • Python实现SMTP发送邮件(四)-添加附件 [Python]纯文本查看复制代码 ? 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 ...
  • 可以使用Python的email模块来实现带有附件邮件发送。 SMTP (Simple Mail Transfer Protocol)邮件传送代理 (Mail Transfer Agent,MTA) 程序使用SMTP协议来发送电邮到接收者的邮件服务器。SMTP协议只能用来发送...
  • 主要介绍了python selenium实现发送附件邮件代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
  • 这是一个例子:msg = MIMEMultipart()msg['Subject'] = subjectmsg['From'] = from_addrmsg['To'] = COMMASPACE.join(to_addrs_list)msg['Date'] = formatdate(localtime = True)msg['Cc'] = COMMASPACE.join(cc_...
  • # coding: utf-8 from email.mime....这封邮件python发送的" attachfilepath="d:\\test.xlsx" send_mail(send_address, send_password, receive_address, title,content ,file=attachfilepath) print('success')
  •           构造邮件内容(件人、收件人、主题、正文、附件等) (2)email 模块下有 mime 包,mime 包下常用的有三个模块:(text、image、multipart)     ① MIMETex:(纯文本、HTML页面),参数...
  • python发送邮件附件

    2021-02-03 02:23:19
    /usr/bin/env python2 # -*- coding:utf-8 -*-34 import smtplib5 from email.mime.multipart import MIMEMultipart6 from email.mime.text import MIMEText7 from email.mime.application import MIMEApplicati...
  • python3发送邮件代码:import smtplibfrom email.mime.text import MIMETextfrom email.utils import formatdate#设置服务器所需信息#163邮箱服务器地址mail_host = 'smtp.163.com'#163用户名mail_user = 'h*****@...
  • time,os,zipfile,mimetypesclassSendEmail():"""...
  • Python自动发送邮件添加附件的源代码,真特定网站,比较具有参考价值
  • python 发送邮件附件

    千次阅读 2018-09-29 16:48:42
    用授权码登录发送邮件附件 需要对邮件进行POP3/SMTP服务设置,例如qq邮箱: 特别提示- ---> 千万不要泄漏自己的授权码  这里的邮箱的域名与端口根据自己的实际邮箱去填写(这是qq邮箱) ...
  • sendmail配置smtp认证是个坑sendmail配置smtp认证是个坑sendmail配置smtp.../usr/bin/env python#coding=utf-8import sysimport smtplibfrom email.mime.multipart import MIMEMultipart#from email.mime.image i...
  • 主要为大家详细介绍了python smtplib发送附件邮件小程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • 添加邮件附件 3。将Excel附件添加到正文中""" to_addr表示群发集,使用形如('abc.163.com,add.163.com,3243@qq.com') html表示要展示在正文中的网页或者表格等。 password字段表示邮箱的验证码,在打开smtp协议...
  • 一、smtplib模块:主要通过SMTP类与邮件系统进行交互。使用方法如下:1.实例化一个SMTP对象:s = smtplib.SMTP...发送邮件:s.sendmail(件人邮箱,收件人邮箱,发送内容)4.断开连接:s.close()二、email模块:...
  • 这是python发送邮件的源码,支持群发和添加邮件, 文章中有免费下载地址,这里是土豪专用下载地址,
  • python发邮件(带附件)

    千次阅读 2019-09-28 17:26:06
    这就需要在邮件添加附件, 或者直接在邮件正文中展示. 可以使用python脚本实现此功能. **未解决: **发送附件时, 不管附件的源格式是什么, 接收到的邮件中的附件文本内容都是UTF-8编码, 但是excel不支持UTF-8格式的...
  • python发送邮件并附带.zip附件

    千次阅读 2020-04-14 21:10:01
    利用python自带的zipfile库,具体思路是通过os.walk()函数遍历某一文件夹的所有文件,再把这些文件写入到压缩包内。 step1:利用zipfile库的ZipFile函数创建一个压缩包(.zip类型)的对象 step...
  • Python3 发送附件邮件 附件名如何引入变量 # 构建附件1,传送桌面目录下的2.txt文件 att1 = MIMEText(open(2.txt,'rb').read(), 'base64', 'utf-8') att1['Content-Type'] = 'application/octet-stream' ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 5,404
精华内容 2,161
关键字:

python发送邮件添加附件

python 订阅