from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.header import Header
from email.mime.image import MIMEImage
from email.utils import parseaddr, formataddr
import smtplib
import os
class Sendemail:
def __init__(self):
self.sender = ''
self.subject = ''
self.smtp_server = ''
self.recipients = []
self.message = ''
self.Cc = ''
self.msg = MIMEMultipart('alternative')
self.attachment_id = 0
def server(self, smtp_ipaddress, smtp_port=25):
self.smtp_server = smtplib.SMTP(smtp_ipaddress, smtp_port)
def login(self, account, password):
"""
:param sender: str
:param password: str
:return:
"""
if self.sender == '':
self.sender = account
try:
self.smtp_server.login(account, password)
except Exception as e:
print(e)
@staticmethod
def __format_addr(address):
name, addr = parseaddr(address)
return formataddr((Header(name, 'utf-8').encode(), addr))
def add_image(self, image_path):
attachment_id = str(self.attachment_id)
image = MIMEImage(open(image_path, 'rb').read())
image.add_header('Content-ID', '%s' % attachment_id)
html_image = '<br><img src="cid:%s" alt="%s" width="50%%" height="50%%">' % (attachment_id, os.path.basename(image_path).split('.')[0])
self.msg.attach(image)
self.message += html_image
self.attachment_id += 1
def add_attachments(self, file_path):
att = MIMEApplication(open(file_path, 'rb').read())
att.add_header("Content-Type", 'application/octet-stream')
att.add_header("Content-Disposition", 'attachment', filename=os.path.basename(file_path))
att.add_header('X-Attachment-Id', str(self.attachment_id))
self.msg.attach(att)
def sendemail(self):
self.msg['From'] = self.__format_addr(self.sender)
self.msg['To'] = self.__format_addr(",".join(self.recipients))
self.msg['Cc'] = self.__format_addr(",".join(self.Cc))
self.msg['Subject'] = Header(self.subject, 'utf-8').encode()
self.msg.attach(MIMEText(self.message, 'html', 'utf-8'))
try:
self.smtp_server.sendmail(self.sender, self.recipients, self.msg.as_string())
self.smtp_server.quit()
except Exception as e:
print(e)
if __name__ == '__main__':
mail = Sendemail()
mail.server('smtp.126.com')
mail.login('xxxxxxxx@126.com', 'xxxxxxxx')
mail.subject = '测试邮件'
mail.recipients = ['xxxxxxxxxx@qq.com']
mail.Cc = ['xxxxxxxxxx@qq.com']
mail.message = '这是一封通过python发送又一个的测试邮件'
mail.add_image(r'C:\Users\gaoyuanzhi\Desktop\aaa.jpg')
mail.add_image(r'C:\Users\gaoyuanzhi\Desktop\bbb.jpg')
mail.add_attachments(r'C:\Users\gaoyuanzhi\Desktop\aaa.jpg')
mail.sendemail()