简单邮件传输协议(SMTP)用作使用Python处理电子邮件传输的协议。它用于在电子邮件服务器之间路由电子邮件。这是一个应用程序层协议,它允许用户将邮件发送到另一个。收件人使用协议 POP(邮局协议)和 IMAP(Internet邮件访问协议)来检索电子邮件。
当服务器侦听来自客户端的TCP连接时,它将在端口587上启动连接。
Python提供了一个 smtplib 模块,该模块定义了一个SMTP客户端会话对象,该对象用于将电子邮件发送到Internet机器。为此,必须使用import语句导入 smtplib 模块。
$ import smtplib
SMTP对象用于电子邮件传输。以下语法用于创建smtplib对象。
import smtplib smtpObj = smtplib.SMTP(host, port, local_hostname)
它接受以下参数。
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 SMTP服务器发送的。在这种情况下,可以将Gmail用作SMTP服务器,而不是通过端口587使用localhost。
使用以下语法。
链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-sending-email.html
来源:LearnFk无涯教程网
$ smtpObj = smtplib.SMTP("gmail.com", 587)
在这里,需要使用Gmail用户名和密码登录Gmail帐户。为此,smtplib提供了login()方法,该方法接受发送者的用户名和密码。
如果您使用的是Gmail,这可能会使您的Gmail要求您访问不太安全的应用程序。您需要暂时将其打开才能正常工作。
考虑以下示例。
#!/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")
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)