from email.header import Header from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email import encoders import smtplib import time class EmailPro: def send_mail(self, to_email, code): email_host = 'smtp.163.com' #163 E-mail server address "smtp.163.com" qq mailbox "smtp.qq.com" need permission to open smtp SENDER = ' [email protected] ' # sender's (your mailbox) password = ' xxx ' # E-mail authorization code Receiver = ' [email protected] ' # recipient MSG = MimeMultipart () now = The time.strftime ( ' % Y-M-% D%% H:% M:% S ' , time.localtime (Time .time ())) Subject = now + ' mailbox activated ' H = Header ( ' sender nickname custom ' ,'. 8-UTF ' ) h.append ( ' <[email protected]> ' , ' ASCII ' ) MSG [ " the From " ] = H MSG [ ' the Subject ' ] = Subject # title MSG [ ' the To ' ] = ' XXX ' # ... recipient ... Signature = ' '' \ \ t by You are the n-MOST is available for purchase! \ the n-\ t click the button below to activate the mailbox '' ' # text = MimeText (Signature,' Plain ') # Signature #msg.attach (text) # Body - Image can be put through the html format image, so that lines 25 and 26 to be annotated mail_msg = F '' ' <P> \ n-\ T MOST are available for purchase by You </ P>! <P > \ n \ t activate the button below mailbox </ P> <button style = "background-Color: # 31708f; border-RADIUS: 3px"> <a the href = "http://127.0.0.1:8000/user / email / active / email = { to_email} & code = {code} "style =" color:? white; font-size: 25px; text-decoration: none "> activate mailbox </a> </ Button> <P> <IMG the src = "CID: image1"> </ P> '' ' msg.attach (MimeText (mail_msg, ' HTML ' , ' UTF-. 8 ')) # Specify the image to the current directory fp = Open (r ' E: \ rent_house \ Media \ Banner \ 3.jpg ', ' RB ' ) msgImage = MIMEImage (fp.read ()) fp.close () # definition picture ID, referenced in the HTML text msgImage.add_header ( ' the Content-ID ' , ' <image1> ' ) msg.attach ( msgImage) # ctype = 'file application / OCTET-Stream' # MainType, subtype = ctype.split ( '/',. 1) # Annex - image # image MIMEImage = (Open (r'E: \ rent_house \ Media \ Banner \. 3 .jpg ',' RB '). Read (), = _subtype subtype) # image.add_header (' the Content-Disposition ',' Attachment ', filename =' IMG.jpg') # msg.attach(image) # 附件-文件 # file = MIMEBase(maintype, subtype) # file.set_payload(open(r'E:\rent_house\apps\utils\response.py', 'rb').read()) # file.add_header('Content-Disposition', 'attachment', filename='test.txt') # encoders.encode_base64(file) # msg.attach(file) # 发送 smtp = smtplib.SMTP() smtp.connect(email_host, 25) smtp.login(sender, password) smtp.sendmail(sender, to_email, msg.as_string()) smtp.quit() print('success') email_worker = EmailPro()