一直想着给框架添加邮件发送功能、所以整理下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邮件发送功能的具体实现代码,希望对大家的学习有所帮助。

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
