python之-邮件发送

Python之-邮件发送

模块使用

  1. smtplib模块
  2. time模块 (用于时间延迟)
  3. email模块中 header,mime(text,multipart)的使用

header : 用于定义mail头部信息
mime.text : 用于定义邮件正文文本功能
mime.multipart : 用于定义邮件附件功能

#!/usr/bin/python3
#coding:utf-8

import smtplib
from time import sleep
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

class mailScript(object):
    
    def __init__(self,smtpServer, sender, password, receiver):
        self.smtpServer = smtpServer
        self.sender = sender 
        self.password = password
        self.receiver = receiver
        
    def mailAction(self):
        for num in range(1,101):
            mail_title = '测试%s' %num
            message = MIMEMultipart()
            message['From'] = self.sender
            message['To'] = self.receiver
            message['Subject'] = Header(mail_title, 'utf-8')
        
            message.attach(MIMEText('Virus test.', 'plain', 'utf-8'))
            virus = MIMEText(open('./sample_1028/'\
                                  +str(num)+'', 'rb').read(), 'base64', 'utf-8')
            virus["Content-Type"] = 'application/octet-stream'
            virus["Content-Disposition"] = \
                    'attachment; filename="test%s"' %(num)
            message.attach(virus)

            try:
                smtp = smtplib.SMTP()   # 创建一个连接
                smtp.connect(self.smtpServer)
                smtp.login(self.sender, self.password)
                #smtp.login(username, password)
                smtp.sendmail(self.sender, self.receiver, \
                              message.as_string())  # 填入邮件的相关信息并发送
                sleep(15)
                print("邮件发送成功!!!")
                smtp.quit()
            #except smtplib.SMTPException, e:
            except BaseExcetion, e:
                print("邮件发送失败!!!")
                print(e)

    def _help(self):
        strings = "有的注释是有特殊意义的\
                并非注释比如qq的方式就需要输入\
                username属性根据自己需求定。"
        #username = '294****@qq.com'
        """这是qq的"""
        #mail_body = 'Virus test.'
        # 创建一个实例
        """发送正文只包含简单文本的邮件,引入MIMEText即可"""
        #message = MIMEText(mail_body, 'plain', 'utf-8')
        """上面那个是发送正文啊文本之类的\
                mail_body属性定义的就是内容"""
        print(strings)
   
if __name__=="__main__":
    sender = 'j******@163.com'
    receiver = 't****@f****.com'
    smtpServer = 'smtp.163.com'
    password = '*****'
    mail = mailScript(smtpServer, sender, password, receiver)
    #这里的密码不是账户密码而是授权码smtp
    mail.mailAction()


发布了39 篇原创文章 · 获赞 13 · 访问量 3346

猜你喜欢

转载自blog.csdn.net/qq_30036471/article/details/103206761