python send email
pythonSend email
Preparation
The two main ways to send emails in python are smtplib and email Modules, the following mainly explains these two modules
#Before explaining, you need to prepare at least two test mailboxes, in which smtplib must be turned on in the mailbox settings. The protocol can be sent and received
smtplib
##smtplib.SMTP( [host [, port [, local_hostname [,
time<a href="http://www.php.cn/wiki/1268.html" target="_blank">out]]]])</a>
hostis the server of the
SMTPhost, where the
163mailbox is
smtp.163.com, others can be found online,
portis the port number, the default here is
25,
local_hostnameis your host
SMTP, if
SMTPis on your local machine, you only need to specify the server address as
localhost.
timeoutis the set connection limit time. If the connection is not connected after this time, an error will occur
SMTP.
set<a href="http://www.php.cn/code/8209.html" target="_blank">_debuglevel(level)</a>: Set whether to
debug mode. The default is False, which is non-debugging mode, which means no debugging information will be output. If set to
1, it means output debugging information
- ##SMTP.connect([host[, port]])
: Connect to the specified
smtp
server. The parameters representsmpt
host and port respectively. Note: You can also specify the port number in thehost
parameter (for example:smpt.yeah.net:25
), so there is no need to give theport
parameter.
- SMTP.login(user, passw
ord
)<a href="http://www.php.cn/wiki/1360.html" target="_blank"> Log in to the server, here </a>user
is the user name of the email, but thepassword
here is not the password of your email. When you turn onSMTP
, you will be prompted to set a password, here The password is the corresponding password
##SMTP.s
- end
mail(from_addr, [to_addrs, ], msg[, mail_options, rcpt_options])
Send an email, <a href="http://www.php.cn/wiki/1048.html" target="_blank">from_addr</a> is the sender, which is your email address,
to_addris the address of the recipient, of course it can be used here Fill in multiple email accounts and send to multiple accounts. If there are multiple accounts, you need to use a list to pass parameters
##emialSMTP .quit()
- Disconnect
email
module is used to process emails Messages, including MIME and other message documents based onRFC 2822. It is very simple to use these modules to define the content of emails. The classes it includes are (more detailed introduction can be found at: http://docs.python.org/library/email.mime.html):
##class: A subclass ofemail.mime.base.MIMEBase(_
##class email.mime.multipart.MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]] ]- main
type, _subtype, **_params)
: This is <a href="http://www.php.cn/wiki/164.html" target="_blank">MIME</a> A base class. There is generally no need to create an instance when using it. Where _maintype is the content type, such as text or image. _subtype is the <a href="http://www.php.cn/wiki/646.html" target="_blank">minor type</a> type of the content, such as
plainor
gif
.
**_paramsis a dictionary, passed directly to Message.add_<a href="http://www.php.cn/wiki/109.html" target="_blank">head</a>er().
MIMEBaseMIMEMultipart A subclass of, a collection of multiple
:- MIME
#class email.mime.application.MIMEApplication(_data[, _subtype[, _encoder[, **_params]]])
objects
,_subtype
default value ismixed
. boundary is the boundary ofMIMEMultipart
. The default boundary is countable. This class is used when sending attachments.
.
##class email.mime.audio.MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]])
:
MIMEAudioObject
ordinary text emails
- class email. mime.text.MIMEText(_text[, _subtype[, _charset]])
:
MIME
text object, where_text
is the email content,_subtype
email Type, can betext/plain
(ordinary text email),html/plain
(html email),_charset
encoding, can begb2312
etc.
##Ordinary textE-mail sending
- , the key is to
MIMEText中_subtype
is set to
plain. First import
smtpliband
mimetext. Create
smtplib.smtpinstance,
connectserver, send after
login, the specific code is as follows*
# 一个格式化邮件的函数,可以用来使用def _format_addr(s): name, addr = parseaddr(s) return formataddr(( Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) from_addr='××××××××' #你的邮箱地址from_password='×××××××' #你的密码# to_email='chenjiabing666@yeah.net'to_email='××××××' #要发送的邮箱地址msg=MIMEText('乔装打扮,不择手段','plain','utf-8') #这里text=乔装打扮,不择手段msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr) #格式化发件人msg['To'] = _format_addr(u'管理员 <%s>' % to_email) #格式化收件人msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode() #格式化主题stmp='smtp.163.com'server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password) #登录server.set_debuglevel(1) #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string()) #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表
Send html email
MIMETextto send, but the _subType
can be set to html, the detailed code is as follows:
def _format_addr(s): name, addr = parseaddr(s) return formataddr(( Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) from_addr='××××××××' #你的邮箱地址from_password='×××××××' #你的密码# to_email='chenjiabing666@yeah.net'to_email='××××××' #要发送的邮箱地址html="""<p><h1 style="color:red">大家好</h1></p>"""msg=MIMEText(html,'html','utf-8') #这里text=html,设置成html格式的msg['From'] = _format_addr(u'Python爱好者 <%s>' % from_addr) #格式化发件人msg['To'] = _format_addr(u'管理员 <%s>' % to_email) #格式化收件人msg['Subject'] = Header(u'来自SMTP的问候……', 'utf-8').encode() #格式化主题stmp='smtp.163.com'server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password) #登录server.set_debuglevel(1) #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string()) #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表
Sending attachments
MIMEMultipart()instance, and then construct the attachment. If there are multiple attachments, It can be constructed in sequence and finally sent using smtplib.smtp
. The specific strength is as follows:
from email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport smtplibfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.header import Headerdef _format_addr(s): name, addr = parseaddr(s) return formataddr(( Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) from_addr='××××××××' #你的邮箱地址from_password='×××××××' #你的密码# to_email='chenjiabing666@yeah.net'to_email='××××××' #要发送的邮箱地址msg=MIMEMultipart() #创建实例text=MIMEText('<h2 style="color:red">陈加兵</h2><br/><p>大家好</p>','html','utf-8') msg.attach(text) #添加一个正文信息,这里实在正文中显示的信息#创建一个文本附件,这里是从指定文本中读取信息,然后创建一个文本信息att1=MIMEText(open('/home/chenjiabing/文档/MeiZi_img/full/file.txt','rb').read(),'plain','utf-8') att1["Content-Type"] = 'application/octet-stream' #指定类型att1["Content-Disposition"] = 'attachment; filename="123.txt"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1) #向其中添加附件img_path='/home/chenjiabing/文档/MeiZi_img/full/file.jpg' #图片路径image=MIMEImage(open(img_path,'rb').read()) #创建一个图片附件image.add_header('Content-ID','<0>') #指定图片的编号,这个会在后面用到image.add_header('Content-Disposition', 'attachment', filename='test.jpg') image.add_header('X-Attachment-Id', '0') msg.attach(image) #添加附件stmp='smtp.163.com'server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password) #登录server.set_debuglevel(1) #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string()) #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表
Embed the picture into the text message
from email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport smtplibfrom email.mime.image import MIMEImagefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.header import Headerdef _format_addr(s): name, addr = parseaddr(s) return formataddr(( Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) from_addr='××××××××' #你的邮箱地址from_password='×××××××' #你的密码# to_email='chenjiabing666@yeah.net'to_email='××××××' #要发送的邮箱地址msg=MIMEMultipart() #创建实例html="""<html><head></head><body><p>下面演示嵌入图片</p><section><img src='cid:0' style='float:left'/><img src='cid:1' style='float:left'/></setcion></body></html>"""text=MIMEText('<h2 style="color:red">陈加兵</h2><br/><p>大家好</p>','html','utf-8') msg.attach(text) #添加一个正文信息,这里实在正文中显示的信息#创建一个文本附件,这里是从指定文本中读取信息,然后创建一个文本信息att1=MIMEText(open('/home/chenjiabing/文档/MeiZi_img/full/file.txt','rb').read(),'plain','utf-8') att1["Content-Type"] = 'application/octet-stream' #指定类型att1["Content-Disposition"] = 'attachment; filename="123.txt"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1) #向其中添加附件## 创建一个图片附件img_path='/home/chenjiabing/文档/MeiZi_img/full/file.jpg' #图片路径image=MIMEImage(open(img_path,'rb').read()) #创建一个图片附件image.add_header('Content-ID','<0>') #指定图片的编号,image.add_header('Content-Disposition', 'attachment', filename='test.jpg') image.add_header('X-Attachment-Id', '0') msg.attach(image) #添加附件#创建第二个图片附件img_path_1='/home/chenjiabing/文档/MeiZi_img/full/test.jpg' #图片路径image1=MIMEImage(open(img_path,'rb').read()) #创建一个图片附件image1.add_header('Content-ID','<1>') #指定图片的编号,这个就是在上面对应的cid:1的那张图片,因此这里的编号一定要对应image1.add_header('Content-Disposition', 'attachment', filename='img.jpg') image1.add_header('X-Attachment-Id', '0') msg1.attach(image) #添加附件stmp='smtp.163.com'server=smtplib.SMTP(stmp,port=25,timeout=30) #连接,设置超时时间30sserver.login(from_addr,from_password) #登录server.set_debuglevel(1) #输出所有的信息server.sendmail(from_addr,to_email,msg.as_string()) #这里的as_string()是将msg转换成字符串类型的,如果你想要发给多个人,需要讲to_email换成一个列表
The above is the detailed content of python send email. For more information, please follow other related articles on the PHP Chinese website!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

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.

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.

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.

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.
