Home Backend Development Python Tutorial Python implements SMTP email sending

Python implements SMTP email sending

Mar 02, 2017 pm 04:45 PM
python smtp send mail

一直想着给框架添加邮件发送功能、所以整理下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__ == &#39;__main__&#39;:
 SendEmail.send_email_text()
Copy after login

这只是纯文本的内容、可以支持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(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename="测试报告.xml")
  mime.add_header(&#39;Content-ID&#39;, &#39;<0>&#39;)
  mime.add_header(&#39;X-Attachment-Id&#39;, &#39;0&#39;)
  # 把附件的内容读进来:
  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 "邮件发送失败"
Copy after login


以上就是python邮件发送功能的具体实现代码,希望对大家的学习有所帮助。

更多python实现SMTP邮件发送相关文章请关注PHP中文网!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Can visual studio code run python Can visual studio code run python Apr 15, 2025 pm 08:00 PM

VS Code not only can run Python, but also provides powerful functions, including: automatically identifying Python files after installing Python extensions, providing functions such as code completion, syntax highlighting, and debugging. Relying on the installed Python environment, extensions act as bridge connection editing and Python environment. The debugging functions include setting breakpoints, step-by-step debugging, viewing variable values, and improving debugging efficiency. The integrated terminal supports running complex commands such as unit testing and package management. Supports extended configuration and enhances features such as code formatting, analysis and version control.

Can vs code run python Can vs code run python Apr 15, 2025 pm 08:21 PM

Yes, VS Code can run Python code. To run Python efficiently in VS Code, complete the following steps: Install the Python interpreter and configure environment variables. Install the Python extension in VS Code. Run Python code in VS Code's terminal via the command line. Use VS Code's debugging capabilities and code formatting to improve development efficiency. Adopt good programming habits and use performance analysis tools to optimize code performance.

See all articles