一直想着给框架添加邮件发送功能、所以整理下python下邮件发送功能
首先python是支持邮件的发送、内置smtp库、支持发送纯文本、HTML及添加附件的邮件。之后是邮箱、像163、qq、新浪等邮箱默认关闭SMTP服务,需要我们手动打开,打开后通过发件人邮箱、授权密码 通过发件人的SMTP服务发送
代码如下:
#!/usr/bin/env python # -*- coding: utf_8 -*- from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.multipart import MIMEBase from email import encoders from email.header import Header from email.utils import parseaddr, formataddr import smtplib class SendEmail: outbox = "pythondldysl01@163.com" # 发件箱地址 password = "wxqcl258258" # 授权密码 不是邮箱登录密码 inbox = "xxx@qq.com" # 收件箱地址 smtp_server = "smtp.163.com" # 发件箱服务器地址 def __init__(self): pass @classmethod def _format_address(cls, text): name, address = parseaddr(text) return formataddr((Header(name, "utf-8").encode(), address)) @classmethod def send_email_text(cls): msg = MIMEText("测试smtp邮件发送功能", "plain", "utf-8") # 第一个参数:邮件正文 # 第二个参数:邮件类型 纯文本 # 第三个参数:编码 msg["From"] = SendEmail._format_address("来自163的一封邮件 <%s>" % SendEmail.outbox) # 发件人姓名与发件箱地址 msg["To"] = SendEmail._format_address("管理员 <%s>" % SendEmail.inbox) # 收件人姓名与收件箱地址 msg["Subject"] = Header("来自SMTP的问候", "utf-8").encode() # 邮件标题 try: server = smtplib.SMTP(SendEmail.smtp_server, 25) # 构造smtp服务器连接 # server.set_debuglevel(1) # debug输出模式 默认关闭 server.login(SendEmail.outbox, SendEmail.password) # 登录smtp服务器 server.sendmail(SendEmail.outbox, [SendEmail.inbox], msg.as_string()) # 发送邮件 server.quit() print "邮件发送成功" except Exception, e: print str(e) print "邮件发送失败" if __name__ == '__main__': SendEmail.send_email_text()
这只是纯文本的内容、可以支持HTML格式的内容、修改内容如下:
msg = MIMEText("测试smtp邮件发送功能", "plain", "utf-8")
内容修改成HTML格式、 “plain”改成 “html”
最后是添加附件的邮件
代码如下:
@classmethod def send_email_multipart(cls): msg = MIMEMultipart() msg["From"] = SendEmail._format_address("来自163的一封邮件 <%s>" % SendEmail.outbox) # 发件人姓名与发件箱地址 msg["To"] = SendEmail._format_address("管理员 <%s>" % SendEmail.inbox) # 收件人姓名与收件箱地址 msg["Subject"] = Header("来自SMTP的问候", "utf-8").encode() # 邮件标题 msg.attach(MIMEText("测试添加附件的smtp邮件发送功能", "plain", "utf-8")) with open("E:\\work\\python project\\CreateProject\\20160421140953.xml", "rb") as f: # 设置附件的MIME和文件名 mime = MIMEBase("xml", "xml", filename="测试报告.xml") # 加上必要的头信息 mime.add_header('Content-Disposition', 'attachment', filename="测试报告.xml") mime.add_header('Content-ID', '<0>') mime.add_header('X-Attachment-Id', '0') # 把附件的内容读进来: mime.set_payload(f.read()) # 用Base64编码: encoders.encode_base64(mime) # 添加到MIMEMultipart: msg.attach(mime) try: server = smtplib.SMTP(SendEmail.smtp_server, 25) # 构造smtp服务器连接 # server.set_debuglevel(1) # debug输出模式 默认关闭 server.login(SendEmail.outbox, SendEmail.password) # 登录smtp服务器 server.sendmail(SendEmail.outbox, [SendEmail.inbox], msg.as_string()) # 发送邮件 server.quit() print "邮件发送成功" except Exception, e: print str(e) print "邮件发送失败"
以上就是python邮件发送功能的具体实现代码,希望对大家的学习有所帮助。
更多python实现SMTP邮件发送相关文章请关注PHP中文网!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.