Python使用SMTP发送电子邮件

Python使用SMTP发送电子邮件

简单邮件传输协议(SMTP)是使用Python处理电子邮件传输的协议。它用于在电子邮件服务器之间路由电子邮件。它是一个应用层协议,允许用户向另一个用户发送邮件。收件人使用 POP(邮局协议)IMAP(互联网消息访问协议) 协议检索电子邮件。

Python使用SMTP发送电子邮件

当服务器监听客户端的TCP连接时,它在端口587上初始化一个连接。

Python提供了一个 smtplib 模块,该模块定义了用于向Internet机器发送电子邮件的SMTP客户端会话对象。为此,我们必须使用import语句导入 smtplib 模块。

$ import smtplib

SMTP对象用于电子邮件传输。使用以下语法来创建smtplib对象。

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

它接受以下参数。

  • host: 它是运行您的SMTP服务器的机器的主机名。在这里,我们可以指定服务器的IP地址,如(https://www.deepinout.com)或localhost。这是一个可选参数。
  • port: 这是主机机器监听SMTP连接的端口号。默认情况下为25。
  • local_hostname: 如果SMTP服务器运行在您的本地机器上,我们可以提供本地机器的主机名。

SMTP对象的sendmail()方法用于将邮件发送到所需的机器。语法如下。

smtpObj.sendmail(sender, receiver, message)  

示例

#!/usr/bin/python3  
import smtplib  
sender_mail = 'sender@fromdomain.com'  
receivers_mail = ['reciever@todomain.com']  
message = """From: From Person %s 
To: To Person %s 
Subject: Sending SMTP e-mail  
This is a test e-mail message. 
"""%(sender_mail,receivers_mail)  
try:  
   smtpObj = smtplib.SMTP('localhost')  
   smtpObj.sendmail(sender_mail, receivers_mail, message)  
   print("Successfully sent email")  
except Exception:  
   print("Error: unable to send email")  

从Gmail发送电子邮件

有些情况下,我们使用Gmail的SMTP服务器来发送电子邮件。在这种情况下,我们可以将Gmail作为SMTP服务器,而不是使用本地主机和端口587。

使用以下语法。

$ smtpObj = smtplib.SMTP("gmail.com", 587)   

这里,我们需要使用Gmail的用户名和密码登录Gmail账户。为此,smtplib提供了login()方法,该方法接受发件人的用户名和密码。

这可能会导致您的Gmail要求您访问较不安全的应用程序。您需要临时启用此选项才能正常工作。

Python使用SMTP发送电子邮件

考虑以下示例。

示例

#!/usr/bin/python3  
import smtplib  
sender_mail = 'sender@gmail.com'  
receivers_mail = ['reciever@gmail.com']  
message = """From: From Person %s 
To: To Person %s 
Subject: Sending SMTP e-mail  
This is a test e-mail message. 
"""%(sender_mail,receivers_mail)  
try:  
   password = input('Enter the password');  
   smtpObj = smtplib.SMTP('gmail.com',587)  
   smtpobj.login(sender_mail,password)  
   smtpObj.sendmail(sender_mail, receivers_mail, message)  
   print("Successfully sent email")  
except Exception:  
   print("Error: unable to send email")  

发送HTML邮件

我们可以通过指定MIME版本、内容类型和字符集来格式化消息中的HTML。

考虑以下示例。

示例

#!/usr/bin/python3  
import smtplib  
sender_mail = 'sender@fromdomain.com'  
receivers_mail = ['reciever@todomain.com']  
message = """From: From Person %s 
To: To Person %s 

MIME-Version:1.0 
Content-type:text/html 


Subject: Sending SMTP e-mail  

<h3>Python SMTP</h3> 
<strong>This is a test e-mail message.</strong> 
"""%(sender_mail,receivers_mail)  
try:  
   smtpObj = smtplib.SMTP('localhost')  
   smtpObj.sendmail(sender_mail, receivers_mail, message)  
   print("Successfully sent email")  
except Exception:  
   print("Error: unable to send email")  

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程