search
HomeBackend DevelopmentPython TutorialDetailed introduction to Python using SMTP to send emails

Python uses SMTP to send emails.

SMTP (Simple Mail Transfer Protocol) is a simple mail transfer protocol. It is a set of The rules for transmitting mail from the source address to the destination address, which controls how the mail is transferred.

Python's smtplib provides a very convenient way to send emails. It simply encapsulates the SMTP protocol.

The syntax for Python to create an SMTP object is as follows:

import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

Parameter description:

  • ##host: SMTP server host. You can specify the IP address or domain name of the host such as: w3cschool.cc. This is an optional parameter.

  • port: If you provide the host parameter, you need to specify the port number used by the SMTP service. Generally, the SMTP port number is 25.

  • local_hostname: If SMTP is on your local machine, you only need to specify the server address as localhost.

The Python SMTP object uses the sendmail method to send emails. The syntax is as follows:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]

from_addr: Email sender address.

to_addrs: String list, email sending address.

msg: Send a message

Pay attention to the third parameter here. msg is a string, representing an email. We know that emails generally consist of a title, sender, recipient, email content, attachments, etc. When sending an email, pay attention to the format of msg. This format is the format defined in the smtp protocol.

Example

The following is a simple example of using Python to send emails:

#!/usr/bin/pythonimport smtplib

sender = &#39;from@fromdomain.com&#39;receivers = [&#39;to@todomain.com&#39;]message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
Subject: SMTP e-mail test

This is a test e-mail message.
"""try:
   smtpObj = smtplib.SMTP(&#39;localhost&#39;)
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"except SMTPException:
   print "Error: unable to send email"


Using Python to send emails in HTML format

Python to send HTML The difference between formatted emails and emails that send plain text messages is that _subtype in MIMEText is set to html. The specific code is as follows:

import smtplib  
from email.mime.text import MIMEText  mailto_list=["YYY@YYY.com"] mail_host="smtp.XXX.com"  #设置服务器mail_user="XXX"    #用户名mail_pass="XXXX"   #口令 mail_postfix="XXX.com"  #发件箱的后缀
  def send_mail(to_list,sub,content):  #to_list:收件人;sub:主题;content:邮件内容
    me="hello"+"<"+mail_user+"@"+mail_postfix+">"   #这里的hello可以任意设置,收到信后,将按照设置显示
    msg = MIMEText(content,_subtype=&#39;html&#39;,_charset=&#39;gb2312&#39;)    #创建一个实例,这里设置为html格式邮件
    msg[&#39;Subject&#39;] = sub    #设置主题
    msg[&#39;From&#39;] = me  
    msg[&#39;To&#39;] = ";".join(to_list)  
    try:  
        s = smtplib.SMTP()  
        s.connect(mail_host)  #连接smtp服务器
        s.login(mail_user,mail_pass)  #登陆服务器
        s.sendmail(me, to_list, msg.as_string())  #发送邮件
        s.close()  
        return True  
    except Exception, e:  
        print str(e)  
        return False  if __name__ == &#39;__main__&#39;:  
    if send_mail(mailto_list,"hello","<a href=&#39;http://www.cnblogs.com/xiaowuyi&#39;>小五义</a>"):  
        print "发送成功"  
    else:  
        print "发送失败"

Or you can also specify Content-type as text/html in the message body, as shown in the following example:

#!/usr/bin/pythonimport smtplib

message = """From: From Person <from@fromdomain.com>
To: To Person <to@todomain.com>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test

This is an e-mail message to be sent in HTML format

<b>This is HTML message.</b>
<h1 id="This-nbsp-is-nbsp-headline">This is headline.</h1>
"""try:
   smtpObj = smtplib.SMTP(&#39;localhost&#39;)
   smtpObj.sendmail(sender, receivers, message)         
   print "Successfully sent email"except SMTPException:
   print "Error: unable to send email"


Python sends an email with attachments

To send an email with an attachment, you must first create a MIMEMultipart() instance, then construct the attachment. If there are multiple attachments, they can be constructed in sequence, and finally send using smtplib.smtp.

from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartimport smtplib#创建一个带附件的实例msg = MIMEMultipart()#构造附件1att1 = MIMEText(open(&#39;d:\\123.rar&#39;, &#39;rb&#39;).read(), &#39;base64&#39;, &#39;gb2312&#39;)att1["Content-Type"] = &#39;application/octet-stream&#39;att1["Content-Disposition"] = &#39;attachment; filename="123.doc"&#39;#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1)#构造附件2att2 = MIMEText(open(&#39;d:\\123.txt&#39;, &#39;rb&#39;).read(), &#39;base64&#39;, &#39;gb2312&#39;)att2["Content-Type"] = &#39;application/octet-stream&#39;att2["Content-Disposition"] = &#39;attachment; filename="123.txt"&#39;msg.attach(att2)#加邮件头msg[&#39;to&#39;] = &#39;YYY@YYY.com&#39;msg[&#39;from&#39;] = &#39;XXX@XXX.com&#39;msg[&#39;subject&#39;] = &#39;hello world&#39;#发送邮件try:
    server = smtplib.SMTP()
    server.connect(&#39;smtp.XXX.com&#39;)
    server.login(&#39;XXX&#39;,&#39;XXXXX&#39;)#XXX为用户名,XXXXX为密码
    server.sendmail(msg[&#39;from&#39;], msg[&#39;to&#39;],msg.as_string())
    server.quit()
    print &#39;发送成功&#39;except Exception, e:  
    print str(e)

以下实例指定了Content-type header 为 multipart/mixed,并发送/tmp/test.txt 文本文件:

#!/usr/bin/pythonimport smtplibimport base64

filename = "/tmp/test.txt"# 读取文件内容并使用 base64 编码fo = open(filename, "rb")filecontent = fo.read()encodedcontent = base64.b64encode(filecontent)  # base64sender = &#39;webmaster@tutorialpoint.com&#39;reciever = &#39;amrood.admin@gmail.com&#39;marker = "AUNIQUEMARKER"body ="""
This is a test email to send an attachement.
"""# 定义头部信息part1 = """From: From Person <me@fromdomain.net>
To: To Person <amrood.admin@gmail.com>
Subject: Sending Attachement
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=%s
--%s
""" % (marker, marker)# 定义消息动作part2 = """Content-Type: text/plain
Content-Transfer-Encoding:8bit

%s
--%s
""" % (body,marker)# 定义附近部分part3 = """Content-Type: multipart/mixed; name=\"%s\"
Content-Transfer-Encoding:base64
Content-Disposition: attachment; filename=%s

%s
--%s--
""" %(filename, filename, encodedcontent, marker)message = part1 + part2 + part3try:
   smtpObj = smtplib.SMTP(&#39;localhost&#39;)
   smtpObj.sendmail(sender, reciever, message)
   print "Successfully sent email"except Exception:
   print "Error: unable to send email"

【相关推荐】

1. 分享Python实现SMTP发送邮件图文实例

2. Python 使用SMTP发送邮件的代码小结

3. c#调用qq邮箱smtp发送邮件修改版代码

4. Python使用SMTP发送邮件

5. php smtp发送邮件

6. Python SMTP邮件模块详解

7. python smtplib模块发送SSL/TLS安全邮件实例

The above is the detailed content of Detailed introduction to Python using SMTP to send emails. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

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.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.