1. Zmail sending email script
#! /usr/bin/envpython # -*- coding:utf-8 -*- # __author__ = # https://www.jianshu.com/p/b9e11dbbc9cf # https://github.com/zhangyunhao116/zmail/blob/master/README-cn.md # pip install docx-mailmerge Merge templates of the same format with a set of data # pip install python-docx This module can be used to create, modify and read Microsoft Word documents (.docx files) # https://blog.51cto.com/u_16099200/6873568 python-docx module operates word template # https://github.com/Bouke/docx-mailmerge # https://blog.51cto.com/u_16099267/6372841 docx-mailmerge module operates word template import zmail, traceback # Email information # sender from_mailbox = '[email protected]' # email Password password = 'xxxxxxxx' smtp_server = 'smtp.exmail.qq.com' # recipient to_mailbox = ['[email protected]', '[email protected]'] # CC people cc_mailbox = ['[email protected]', '[email protected]', '[email protected]'] # Email Subject subject = 'Send email test' # Build email html content content_html = """ <html> <head></head> <body> <p>Hello:<br> & amp;nbsp; & amp;nbsp; & amp;nbsp; & amp;nbsp;The following is a test email<br> How are you?<br> Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> </p> <img src="cid:image1"> </body> </html> """ # Add attachments attachment = ['Test attachment.xlsx', 'test.png'] # send email zm = zmail.server(from_mailbox, password, smtp_host='smtp.exmail.qq.com', smtp_port=465, smtp_ssl=True) mail = { 'subject': subject, 'content_html': content_html, 'attachments': attachment } try: zm.send_mail(to_mailbox, mail, cc=cc_mailbox) print('Email sent successfully!') except Exception as e: print(traceback.print_exc()) print('Failed to send email!')
2. smtplib send email script
#! /usr/bin/envpython # -*- coding:utf-8 -*- # __author__ = import smtplib,os from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.image import MIMEImage from email.header import Header import base64 class SendMail(object): def __init__(self, username, passwd, email_host, recv, title, content, cc_list=None, file=None, imagefile=None, ssl=False, port=25, ssl_port=465): ''' :param username: username :param passwd: password :param email_host: smtp server address :param recv: recipient, multiple lists to be passed ['[email protected]','[email protected]'] :param cc_list: CC person, multiple lists to be sent ['[email protected]','[email protected]'] :param title: Email title :param content: Email text :param file: attachment path. If it is not in the current directory, write the absolute path. There is no attachment by default. :param imagefile: Image path. If it is not in the current directory, write an absolute path. There is no image by default. :param ssl: Whether to secure the link, the default is normal :param port: non-secure connection port, default is 25 :param ssl_port: secure connection port, default is 465 ''' self.username = username #username self.passwd = passwd # Password self.recv = recv # Recipients, multiple lists to be passed ['[email protected]','[email protected]] self.cc_list = cc_list # CC people, multiple lists need to be sent ['[email protected]','[email protected]] self.title = title # Email title self.content = content # Email text self.file = file # Attachment path, if it is not in the current directory, write the absolute path self.imagefile = imagefile # Image path, if it is not in the current directory, write the absolute path self.email_host = email_host # smtp server address self.port = port # Common port self.ssl = ssl # Whether the link is safe self.ssl_port = ssl_port #Secure connection port def send_mail(self): # msg = MIMEMultipart() msg = MIMEMultipart('mixed') # Object to send content to if self.file: # Process attachments file_name = os.path.split(self.file)[-1] # Take only the file name, not the path try: f = open(self.file, 'rb').read() except Exception as e: raise Exception('The attachment cannot be opened!!!') else: att = MIMEText(f, "base64", "utf-8") att["Content-Type"] = 'application/octet-stream' # base64.b64encode(file_name.encode()).decode() new_file_name = '=?utf-8?b?' + base64.b64encode(file_name.encode()).decode() + '?=' # This is to process the Chinese name of the file, it must be written like this att["Content-Disposition"] = 'attachment; filename="%s"' % (new_file_name) msg.attach(att) if self.imagefile: try: sendimagefile = open(self.imagefile, 'rb').read() except Exception as e: raise Exception('The picture cannot be opened!!!') else: image = MIMEImage(sendimagefile) image.add_header('Content-ID', '<image1>') # Setting the image id to image1 must correspond to the cid in html msg.attach(image) text_html = MIMEText(self.content, 'html', 'utf-8') msg.attach(text_html) # msg.attach(MIMEText(self.content)) #The content of the email body msg['Subject'] = self.title # Email subject msg['From'] = self.username # Sender account # msg['To'] = ','.join(self.recv) # Receiver account list msg['To'] = Header(','.join(self.recv)) # Receiver account list msg['Cc'] = Header(','.join(self.cc_list)) # CC people, convert the list to a string if self.ssl: self.smtp = smtplib.SMTP_SSL(self.email_host, port=self.ssl_port) else: self.smtp = smtplib.SMTP(self.email_host, port=self.port) # The object of the sending mail server self.smtp.login(self.username, self.passwd) try: self.smtp.sendmail(self.username, self.recv + self.cc_list, msg.as_string()) pass except Exception as e: print('An error occurred...', e) else: print('Sent successfully!') self.smtp.quit() if __name__ == '__main__': """ Sending pictures in the text: Because it contains unauthorized information, NetEase mailbox defines it as spam and reports 554 DT:SPM: <p><img src="cid:image1"></p> """ m = SendMail( username='[email protected]', passwd='xxxx', email_host='smtp.sina.com', recv=['[email protected]', '[email protected]'], cc_list=['[email protected]', '[email protected]', '[email protected]'], title='Send test email', content=""" <html> <head></head> <body> <p>Hi!<br> How are you?<br> Here is the <a href="http://www.baidu.com">link</a> you wanted.<br> </p> <img src="cid:image1"> </body> </html> """, file=r'Test attachment.xlsx', imagefile=r'test.png', ssl=False, ) m.send_mail()
3. Yagmail send email script
#! /usr/bin/envpython # -*- coding:utf-8 -*- # __author__ = # pip install yagmail # https://github.com/kootenpv/yagmail importyagmail yag = yagmail.SMTP(user='[email protected]', password='xxxxxxxx', host='smtp.sina.com') to = ['[email protected]','[email protected]'] # Recipient cc = ['[email protected]','[email protected]'] # Cc person subject = ["[Warm Reminder] Progress"] # Subject picture = r'test.png' # Enter the picture path attached to the text logo = r'logo.png' # Text text = ''' Dear all, In order to improve the security management of funds, we basically send weekly email reminders to collect receivables. This screenshot or attachment is the data on Gemini as of June 19, 2022. If in actual work, the receivables of any payment method are seriously inconsistent with the payment collection time in the agreement, please inform the relevant person in charge, thank you' ''' # Signature (personalized signature) inscribe = """------------------ Feng£fei Operation and Maintenance Development Department XXXXX Technology Co., Ltd. Room x-xxxx, Floor X, No. X, XXXX Road, XXXX District, Beijing Phone: xxxxxxxxxx Email: [email protected] | Website: https://www.cnblogs.com/xwupiaomiao """ contents = [text, yagmail.inline(picture), inscribe, yagmail.inline(logo)] attachments = 'Test attachments.xlsx' # Email attachments yag.send(to=to, cc=cc, subject=subject, contents=contents, attachments=attachments) print("Sent")
Yagmail email example:
The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Python entry skill treeBasic skills Send an email 376823 people are learning the system