by Arjun Krishna Babu
通过Arjun Krishna Babu
如何使用Python发送电子邮件 (How to send emails using Python)
As a learning exercise, I recently dug into Python 3 to see how I could fire off a bunch of emails. There may be more straightforward methods of doing this in a production environment, but the following worked well for me.
作为一项学习练习,我最近研究了Python 3,以了解如何解雇大量电子邮件。 在生产环境中可能会有更直接的方法来执行此操作,但是以下方法对我来说效果很好。
So, here’s a scenario: You have the names and email addresses of a bunch of contacts. And you want to send a message to each one of those contacts, while adding a “Dear [name]” at the top of the message.
因此,这是一个场景:您拥有一堆联系人的姓名和电子邮件地址。 您想向每个联系人发送消息,同时在消息顶部添加“ Dear [name]” 。
For simplicity’s sake you can store the contact details in a file rather than a database. You can also store the template of the message you wish to send in a file.
为简单起见,您可以将联系方式存储在文件中,而不是数据库中。 您也可以将要发送的消息模板存储在文件中。
The smtplib module of Python is basically all you need to send simple emails, without any subject line or such additional information. But for real emails, you do need a subject line and lots of information — maybe even pictures and attachments.
Python的smtplib模块基本上就是您发送简单电子邮件所需要的,而没有任何主题行或此类附加信息。 但是对于真实的电子邮件,您确实需要主题行和大量信息,甚至是图片和附件。
This is where Python’s email package comes in. Keep in mind that it’s not possible to send an email message using the email
package alone. You need a combination of both email
and smtplib
.
这就是Python 电子邮件包的来源。请记住,不可能仅使用email
包发送电子邮件。 您需要同时使用email
和smtplib
。
Be sure to check out the comprehensive official documentation for both of these.
请务必查看这两个文件的综合官方文档。
Here are four basic steps for sending emails using Python:
这是使用Python发送电子邮件的四个基本步骤:
- Set up the SMTP server and log into your account. 设置SMTP服务器并登录到您的帐户。
Create the
MIMEMultipart
message object and load it with appropriate headers forFrom
,To
, andSubject
fields.创建
MIMEMultipart
消息对象,并使用From
,To
和Subject
字段的适当标题加载它。- Add your message body. 添加您的邮件正文。
- Send the message using the SMTP server object. 使用SMTP服务器对象发送消息。
Now let me walk you through the whole process.
现在,让我引导您完成整个过程。
Let’s say you have a contacts file mycontacts.txt
as follows:
假设您有一个联系人文件mycontacts.txt
,如下所示:
user@computer ~ $ cat mycontacts.txt
john johndoe@example.com
katie katie2016@example.com
Each line represents a single contact. We have the name followed by the email address. I’m storing everything in lowercase. I’ll leave it to the programming logic to convert any fields to upper-case or sentence-case if necessary. All of that is pretty easy in Python.
每行代表一个联系人。 我们的名字后面是电子邮件地址。 我将所有内容都以小写形式存储。 如有必要,我将其留给编程逻辑以将任何字段转换为大写或句子大小写。 所有这些在Python中都非常容易。
Next, we have the message template file message.txt
.
接下来,我们有消息模板文件message.txt
。
user@computer ~ $ cat message.txt Dear ${PERSON_NAME}, This is a test message.
Have a great weekend! Yours Truly
Notice the word “${PERSON_NAME}
”? That is a template string in Python. Template strings can easily be replaced with other strings; in this example, ${PERSON_NAME}
is going to be replaced with the actual name of the person, as you’ll see shortly.
注意单词“ ${PERSON_NAME}
”吗? 那是Python中的模板字符串 。 模板字符串可以很容易地用其他字符串替换; 在此示例中, ${PERSON_NAME}
将被替换为该人的实际姓名,您很快就会看到。
Now let’s start with the Python code. First up, we need to read the contacts from the mycontacts.txt
file. We might as well generalize this bit into its own function.
现在让我们从Python代码开始。 首先,我们需要从mycontacts.txt
文件中读取联系人。 我们不妨将此位概括为自己的功能。
The function get_contacts()
takes a filename as its argument. It will open the file, read each line (i.e., each contact), split it into name and email, and then append them into two separate lists. Finally, the two lists are returned from the function.
函数get_contacts()
以文件名作为参数。 它将打开文件,阅读每一行(即每个联系人),将其拆分为姓名和电子邮件,然后将它们附加到两个单独的列表中。 最后,两个列表从函数中返回。
We also need a function to read in a template file (like message.txt
) and return a Template
object made from its contents.
我们还需要一个函数来读取模板文件(例如message.txt
)并返回由其内容构成的Template
对象。
Just like the previous function, this one takes a filename as its argument.
就像上一个函数一样,该函数将文件名作为参数。
To send the email, you need to make use of SMTP (Simple Mail Transfer Protocol). As mentioned earlier, Python provides libraries to handle this task.
要发送电子邮件,您需要使用SMTP(简单邮件传输协议) 。 如前所述,Python提供了处理此任务的库。
In the above code snippet, you’re importing the smtplib
and then creating an SMTP instance that encapsulates an SMTP connection. It takes as parameter the host address and a port number, both of which entirely depends on the SMPT settings of your particular email service provider. For instance, in the case of Outlook, line 4 above would instead be:
在上面的代码片段中,您要导入smtplib
,然后创建一个封装SMTP连接的SMTP实例 。 它以主机地址和端口号作为参数,这两者完全取决于特定电子邮件服务提供商的SMPT设置。 例如,在Outlook中,上述第4行将改为:
s = smtplib.SMTP(host='smtp-mail.outlook.com', port=587)
You should use the host address and port number of your particular email service provider for the whole thing to work.
您应该使用特定电子邮件服务提供商的主机地址和端口号才能正常工作。
MY_ADDRESS
and PASSWORD
above are two variables that holds the full email address and password of the account you’re going to use.
上面的MY_ADDRESS
和PASSWORD
是两个变量,用于保存您要使用的帐户的完整电子邮件地址和密码。
Now would be a good time to fetch the contact information and the message templates using the functions we defined above.
现在将是使用我们上面定义的功能来获取联系信息和消息模板的好时机。
names, emails = get_contacts('mycontacts.txt') # read contacts
message_template = read_template('message.txt')
Now, for each of those contacts, let’s send the mail separately.
现在,对于每个联系人,让我们分别发送邮件。
For each name
and email
(from the contacts file), you’re creating a MIMEMultipart object, setting up the From
, To
, Subject
content-type headers as a keyword dictionary, and then attaching the message body to the MIMEMultipart
object as plain text. You might want to read the documentation to find out more about other MIME types you can experiment with.
对于每个name
和email
(来自联系人文件),您将创建一个MIMEMultipart对象,将From
, To
, Subject
内容类型标题设置为关键字字典,然后将邮件正文作为纯文本附加到MIMEMultipart
对象。 您可能需要阅读文档,以了解有关可以尝试的其他MIME类型的更多信息。
Also note that on line 10 above, I’m replacing ${PERSON_NAME}
with the actual name extracted from the contacts file using the templating mechanism in Python.
还要注意,在上面的第10行中,我使用Python中的模板机制将${PERSON_NAME}
替换${PERSON_NAME}
从联系人文件中提取的实际名称。
In this particular example I’m deleting the MIMEMultipart
object and re-creating it each time you iterate through the loop.
在此特定示例中,我将删除MIMEMultipart
对象,并在每次迭代循环时重新创建它。
Once that is done, you can send the message using the handy send_message() function of the SMTP object you created earlier.
完成后,您可以使用之前创建的SMTP对象的便捷send_message()函数发送邮件。
Here’s the full code:
这是完整的代码:
There you go! I believe the code is now fairly clear.
你去! 我相信代码现在已经很清楚了。
Feel free to copy and tweak it as necessary.
随时复制和调整它。
Apart from the official Python docs, I would also like to mention this resource which helped me a lot.
除了官方的Python文档外,我还想提到这个资源 ,它对我有很大帮助。
Happy coding :)
快乐的编码:)
I originally published this article here. If you liked this article, please hit the small heart below. Thanks!
我最初是在这里发表这篇文章的。 如果您喜欢这篇文章,请打以下小心脏。 谢谢!
翻译自: https://www.freecodecamp.org/news/send-emails-using-code-4fcea9df63f/