Let’s develop a program to send email in python.
让我们开发一个程序以python发送电子邮件。
我们还将使用一个模板文件,该模板文件将在下一部分中显示,并且在发送电子邮件时将使用该模板文件。
我们还将从我们制作的文本文件中选择要发送电子邮件的人的姓名和电子邮件
That sounds better than just a simple task of sending email to static emails. Let’s get started.
这听起来比将电子邮件发送为静态电子邮件的简单任务要好。 让我们开始吧。
We will start defining a simple file which will contain the names and emails of people we want to send the email to. Let’s look at the format of the file we use:
我们将开始定义一个简单的文件,其中包含要发送电子邮件的人员的姓名和电子邮件。 让我们看一下我们使用的文件格式:
contribute [email protected]
shubham [email protected]
This file just contains the name of the person in lowercase characters followed by the email of the person. We use lowercase characters in the name as we will leave it to Python’s capabilities to convert it to proper capital words.
该文件仅以小写字母包含该人的姓名,后跟该人的电子邮件。 我们在名称中使用小写字符,因为它将留给Python将其转换为适当的大写字母的功能。
We will call the above file as contacts.txt
.
我们将上述文件称为contacts.txt
。
When we send an email to users, we usually want to personalize the email with their name so that they feel specifically asked for. We can achieve this by using a template where we can embed the user’s name so that each user receives an email with their name embedded in it.
当我们向用户发送电子邮件时,我们通常希望使用他们的姓名来个性化电子邮件,以便他们感到特别需要。 我们可以通过使用模板来实现此目的,在模板中可以嵌入用户名,以便每个用户都收到一封嵌入了其名称的电子邮件。
Let’s look at the template we are going to use for the program:
让我们看一下我们将用于程序的模板:
Dear ${USER_NAME},
This is an email which is sent using Python. Isn't that great?!
Have a great day ahead!
Cheers
Notice the template string ${USER_NAME}
. This string will be replaced with the name which is contained in the text file we last created.
注意模板字符串${USER_NAME}
。 该字符串将替换为我们上次创建的文本文件中包含的名称。
We will call the above file as message.txt
.
我们将上述文件称为message.txt
。
We can parse the text file by opening it in the r
mode and then iterating through each line of the file:
我们可以通过在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
With this Python function, we Return two lists names
, emails
which contains names and emails of users from the file we pass to it. These will be used in the email template message body.
使用此Python函数,我们返回两个列表names
, emails
,其中包含我们传递给它的文件中的用户的名称和电子邮件。 这些将在电子邮件模板消息正文中使用。
It is time we get the template object in which we make use of the template file we created by opening it in the r
mode and parsing it:
是时候获取模板对象了,在其中使用通过在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)
With this function, we get a Template object which comprises of the contents of the file we specified by filename.
使用此功能,我们得到一个Template对象,该对象包含我们通过filename指定的文件内容。
Till now, we’re ready with the data we want to send in the email and the receiver’s emails. Here, let us look at the steps we need to complete to be ready to send the emails:
到目前为止,我们已经准备好要在电子邮件和收件人的电子邮件中发送的数据。 在这里,让我们看看准备好发送电子邮件所需完成的步骤:
设置用于登录的SMTP连接和帐户凭据
From
, To
, and Subject
fields. 消息对象MIMEMultipart需要使用
From
, To
和Subject
字段的相应标题构造。准备并添加消息正文
使用SMTP对象发送消息
Let’s perform each of these steps here.
让我们在这里执行每个步骤。
To define the SMTO Server connection details, we will make a main() function in which we define our HostLet’s look at a code snippet:
要定义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)
In above main() function, we first received the user names and emails followed by which we constructed the SMTP Server Object. The host
and port
depends on the service provider you use to send emails. For example, in case of Gmail, we will have:
在上面的main()函数中,我们首先收到用户名和电子邮件,然后构造SMTP服务器对象。 host
和port
取决于您用来发送电子邮件的服务提供商。 例如,对于Gmail,我们将具有:
smtp_server = smtplib.SMTP(host='smtp.gmail.com', port=25)
Now, we’re finally ready to send the email.
现在,我们终于可以发送电子邮件了。
Here is a sample program:
这是一个示例程序:
# 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']="JournalDev 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()
We can now see the email arriving at the addresses we defined in the file. To close up, let’s look at the complete code we used for sending emails:
现在,我们可以看到电子邮件到达了文件中定义的地址。 最后,让我们看一下用于发送电子邮件的完整代码:
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']="JournalDev 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()
Note that you will have to replace the host and port property for the email provider you use. For Gmail, I made use of these properties:
请注意,您将必须替换所使用的电子邮件提供程序的host和port属性。 对于Gmail,我利用了以下属性:
smtp_server = smtplib.SMTP(host='smtp.gmail.com', port=587)
When we run this script, we just print the text we send:
运行此脚本时,我们仅打印发送的文本:
Next, in case of Gmail, you might have to turn off the security related to your account. When you configure your email and password and run this script first time, you might receive an email from Gmail like:
接下来,在使用Gmail的情况下,您可能必须关闭与帐户相关的安全性。 当您配置电子邮件和密码并首次运行此脚本时,您可能会收到来自Gmail的电子邮件,例如:
Just follow the instructions given in the email and run the script again and you will see that an email has arrived in the email box you configured in the contacts file like:
只需按照电子邮件中给出的说明进行操作,然后再次运行脚本,您将看到电子邮件已到达您在联系人文件中配置的电子邮件框中,例如:
Reference: Python smtplib Official Docs
参考: Python smtplib官方文档
翻译自: https://www.journaldev.com/19800/python-send-email-smtplib