基于python发送邮件(写成了一个类)

基于python进行邮件的发送

代码如下:

'''
Created on 2021年12月22日

@author: linuxbugs
'''
import smtplib
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.header import Header



class EmailMessage(object):
    def __init__(self):
        self.mail_server = 'smtp.163.com'    #163邮箱服务器地址
        self.mail_user = 'xxxx@163.com'   #163用户名
        self.__mail_pass = 'xxxx'   #密码(部分邮箱为授权码)  
        self.sender_name = 'xxx@163.com'   #邮件发送方邮箱地址
        self.message = MIMEMultipart()
    
    def setup(self,subject,receivers): 
        self.receivers = receivers   #邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发
        self.message['From'] = self.sender_name #发送方信息
        self.message['To'] = ','.join(self.receivers)  #接受方信息
        # self.message['Cc'] = ';'.join(list)  # 抄送
        self.message['Subject'] = Header(subject)  #邮件主题
     
    def addTextMessage(self,message,type='plain',encoding='utf-8'):
        '''邮件文本内容'''
        if type not in ['plain','html']:
            raise TypeError('message type must be plain or html')
        message_text = MIMEText(message,type,encoding)
        self.message.attach(message_text)
    
    def addAnnex(self,path,name='xxx.png',byte=False):
        '''添加附件'''
        if byte == True:
            annex = MIMEApplication(path) # 打开附件
        else:
            annex = MIMEApplication(open(path,'rb').read()) # 打开附件
        annex.add_header('Content-Disposition', 'attachment',filename=name)
        self.message.attach(annex)
        
    def sendEmail(self):
        '''登录并发送邮件'''
        send_status='success'
        try:
            smtpObj = smtplib.SMTP(self.mail_server,port=25)  #连接到服务器
            smtpObj.login(self.mail_user,self.__mail_pass)  #登录到服务器
            #发送
            smtpObj.sendmail(self.sender_name,
                             self.receivers,
                             self.message.as_string()) 
            
            smtpObj.quit()  # 退出
        except smtplib.SMTPException as e:
            send_status='error %s'%e
        return send_status

# if __name__ == '__main__':
#     es = EmailMessage()
#     es.setup('新的测试',['xxxxx@163.com'])
#     # es.addAnnex('/home/linuxbugs/Pictures/20211217_230038.png')
#     es.sendEmail()
#

  

posted @ 2022-01-03 22:46  Linuxbugs  阅读(84)  评论(0编辑  收藏  举报