使用smtplib模块以Python发送电子邮件

时间:2020-02-23 14:43:17  来源:igfitidea点击:

Python smtplib模块可用于在Python程序中发送电子邮件。
这是软件应用程序中非常普遍的要求,smtplib提供了SMTP协议客户端来发送电子邮件。

1.用Python发送电子邮件

让我们开发一个程序,以python发送电子邮件。

  • 我们还将使用一个模板文件,该文件将在下一部分中显示,并在发送电子邮件时使用。

  • 我们还将从我们制作的文本文件中选择要发送电子邮件的人的姓名和电子邮件

这听起来比将电子邮件发送为静态电子邮件的简单任务要好。
让我们开始吧。

1.1)定义包含电子邮件的文件

我们将开始定义一个简单的文件,其中包含要将电子邮件发送给的人的姓名和电子邮件。
让我们看一下我们使用的文件格式:

contribute [email protected]
shubham [email protected]

该文件仅以小写字母包含该人的姓名,后跟该人的电子邮件。
我们在名称中使用小写字符,因为它将留给Python将其转换为适当的大写字母的功能。

我们将上述文件称为" contacts.txt"。

1.2)定义模板

当我们向用户发送电子邮件时,我们通常希望使用他们的姓名来个性化电子邮件,以便他们感到特别需要。
我们可以通过使用模板来实现此目的,在该模板中可以嵌入用户名,以便每个用户都收到一封嵌入了其名称的电子邮件。

让我们看一下我们将用于该程序的模板:

Dear ${USER_NAME}, 
This is an email which is sent using Python. Isn't that great?!

Have a great day ahead! 
Cheers

注意模板字符串" ${USER_NAME}"。
该字符串将替换为我们上次创建的文本文件中包含的名称。

我们将上述文件称为" message.txt"。

1.3)从文件解析电子邮件

我们可以通过以r模式打开文本文件,然后遍历文件的每一行来解析文本文件:

def get_users(file_name):
  names = []
  emails = []
  with open(file_name, mode='r', encoding='utf-8') as user_file:
      for user_info in user_file:
          names.append(user_info.split()[0])
          emails.append(user_infouser.split()[1])
  return names, emails

使用此Python函数,我们返回两个列表"名称","电子邮件",其中包含传递给它的文件中用户的名称和电子邮件。
这些将在电子邮件模板消息正文中使用。

1.4)获取模板对象

现在是时候获得模板对象了,其中我们可以使用通过在r模式下打开它并对其进行解析而创建的模板文件:

def parse_template(file_name):
  with open(file_name, 'r', encoding='utf-8') as msg_template:
      msg_template_content = msg_template.read()
  return Template(msg_template_content)

使用此功能,我们得到一个Template对象,该对象包含我们通过filename指定的文件内容。

2.发送电子邮件如何工作?

到目前为止,我们已经准备好要在电子邮件和收件人电子邮件中发送的数据。
其中让我们看看准备好发送电子邮件所需完成的步骤:

  • 设置用于登录的SMTP连接和帐户凭据

  • 消息对象MIMEMultipart需要使用"发件人","发件人"和"主题"字段的相应标头构造。

  • 准备并添加消息正文

  • 使用SMTP对象发送消息

让我们在这里执行所有这些步骤。

3.定义连接详细信息

为了定义SMTO Server连接的详细信息,我们将创建一个main()函数,其中我们定义HostLet的代码片段外观:

def main():
  names, emails = get_users('contacts.txt') # read user details
  message_template = parse_template('message.txt')

  # set up the SMTP server
  smtp_server = smtplib.SMTP(host='host_address_here', port=port_here)
  smtp_server.starttls()
  smtp_server.login(FROM_EMAIL, MY_PASSWORD)

在上面的main()函数中,我们首先收到用户名和电子邮件,然后构造SMTP服务器对象。
"主机"和"端口"取决于您用来发送电子邮件的服务提供商。
例如,对于Gmail,我们将:

smtp_server = smtplib.SMTP(host='smtp.gmail.com', port=25)

现在,我们终于可以发送电子邮件了。

4.从Python程序发送电子邮件

这是一个示例程序:

# Get each user detail and send the email:
for name, email in zip(names, emails):
  multipart_msg = MIMEMultipart()       # create a message

  # substitute user name with template String
  message = message_template.substitute(USER_NAME=name.title())

  # message parameter definition
  multipart_msg['From']=FROM_EMAIL
  multipart_msg['To']=email
  multipart_msg['Subject']="theitroad Subject"
      
  # add in the message body
  multipart_msg.attach(MIMEText(message, 'plain'))
  
  # send the message via the server
  smtp_server.send_message(multipart_msg)
  del multipart_msg
  
# Terminate the SMTP session and close the connection
smtp_server.quit()
  
if __name__ == '__main__':
  main()

现在,我们可以看到电子邮件到达了我们在文件中定义的地址。
最后,让我们看一下用于发送电子邮件的完整代码:

import smtplib

from string import Template

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

FROM_EMAIL = 'email'
MY_PASSWORD = 'mypassword'

def get_users(file_name):
  names = []
  emails = []
  with open(file_name, mode='r', encoding='utf-8') as user_file:
      for user_info in user_file:
          names.append(user_info.split()[0])
          emails.append(user_info.split()[1])
  return names, emails

def parse_template(file_name):
  with open(file_name, 'r', encoding='utf-8') as msg_template:
      msg_template_content = msg_template.read()
  return Template(msg_template_content)

def main():
  names, emails = get_users('contacts.txt') # read user details
  message_template = parse_template('message.txt')

  # set up the SMTP server
  smtp_server = smtplib.SMTP(host='host-here', port=port-here)
  smtp_server.starttls()
  smtp_server.login(FROM_EMAIL, MY_PASSWORD)

  # Get each user detail and send the email:
  for name, email in zip(names, emails):
      multipart_msg = MIMEMultipart()       # create a message

      # add in the actual person name to the message template
      message = message_template.substitute(USER_NAME=name.title())

      # Prints out the message body for our sake
      print(message)

      # setup the parameters of the message
      multipart_msg['From']=FROM_EMAIL
      multipart_msg['To']=email
      multipart_msg['Subject']="theitroad Subject"
      
      # add in the message body
      multipart_msg.attach(MIMEText(message, 'plain'))
      
      # send the message via the server set up earlier.
      smtp_server.send_message(multipart_msg)
      del multipart_msg
      
  # Terminate the SMTP session and close the connection
  smtp_server.quit()
  
if __name__ == '__main__':
  main()

请注意,您将必须替换所使用的电子邮件提供程序的host和port属性。
对于Gmail,我利用了以下属性:

smtp_server = smtplib.SMTP(host='smtp.gmail.com', port=587)

运行此脚本时,我们仅打印发送的文本:Python发送电子邮件

接下来,如果使用Gmail,则可能必须关闭与帐户相关的安全性。
当您配置电子邮件和密码并首次运行此脚本时,您可能会收到来自Gmail的电子邮件,例如:Gmail安全错误

只需按照电子邮件中的说明进行操作,然后再次运行脚本,您将看到电子邮件已到达您在联系人文件中配置的电子邮件框中,例如:从Python脚本收到的电子邮件