Detailed 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.
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]
#!/usr/bin/pythonimport smtplib sender = 'from@fromdomain.com'receivers = ['to@todomain.com']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('localhost') smtpObj.sendmail(sender, receivers, message) print "Successfully sent email"except SMTPException: print "Error: unable to send email"
Using Python to send emails in HTML formatPython 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='html',_charset='gb2312') #创建一个实例,这里设置为html格式邮件 msg['Subject'] = sub #设置主题 msg['From'] = me msg['To'] = ";".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__ == '__main__': if send_mail(mailto_list,"hello","<a href='http://www.cnblogs.com/xiaowuyi'>小五义</a>"): print "发送成功" else: print "发送失败"
#!/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>This is headline.</h1> """try: smtpObj = smtplib.SMTP('localhost') 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('d:\\123.rar', 'rb').read(), 'base64', 'gb2312')att1["Content-Type"] = 'application/octet-stream'att1["Content-Disposition"] = 'attachment; filename="123.doc"'#这里的filename可以任意写,写什么名字,邮件中显示什么名字msg.attach(att1)#构造附件2att2 = MIMEText(open('d:\\123.txt', 'rb').read(), 'base64', 'gb2312')att2["Content-Type"] = 'application/octet-stream'att2["Content-Disposition"] = 'attachment; filename="123.txt"'msg.attach(att2)#加邮件头msg['to'] = 'YYY@YYY.com'msg['from'] = 'XXX@XXX.com'msg['subject'] = 'hello world'#发送邮件try: server = smtplib.SMTP() server.connect('smtp.XXX.com') server.login('XXX','XXXXX')#XXX为用户名,XXXXX为密码 server.sendmail(msg['from'], msg['to'],msg.as_string()) server.quit() print '发送成功'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 = 'webmaster@tutorialpoint.com'reciever = 'amrood.admin@gmail.com'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('localhost') smtpObj.sendmail(sender, reciever, message) print "Successfully sent email"except Exception: print "Error: unable to send email"
【相关推荐】
5. php 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!

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.

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.

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.

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.
