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包发送电子邮件。 您需要同时使用emailsmtplib

Be sure to check out the comprehensive official documentation for both of these.

请务必查看这两个文件的综合官方文档。

Here are four basic steps for sending emails using Python:

这是使用Python发送电子邮件的四个基本步骤:

  1. Set up the SMTP server and log into your account.设置SMTP服务器并登录到您的帐户。
  2. Create the MIMEMultipart message object and load it with appropriate headers for From, To, and Subject fields.

    创建MIMEMultipart消息对象,并使用FromToSubject字段的适当标题加载它。

  3. Add your message body.添加您的邮件正文。
  4. 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_ADDRESSPASSWORD是两个变量,用于保存您要使用的帐户的完整电子邮件地址和密码。

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.

对于每个nameemail (来自联系人文件),您将创建一个MIMEMultipart对象,将FromToSubject内容类型标题设置为关键字字典,然后将邮件正文作为纯文本附加到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/

使用Python发送电子邮件相关推荐

  1. 发送邮件_使用 Python 发送电子邮件

    在实际运用中,我们可能需要通过电子邮件告诉我们 Python 运行的结果的是否与预期的一致.现在我们就来看一下,怎么通过 Python 发送邮件. 这个示例中我们需要用到的第三方库有: •smtpli ...

  2. python电子邮件地址怎么写_用Python发送电子邮件

    今天给大家分享如何用Python自动发送电子邮件,当我们在云服务器上部署了爬虫,就希望当爬虫发生异常情况的时候能通过自动发送电子邮件来通知我们.因此学会用Python程序自动发送邮件能减轻不少爬虫监控 ...

  3. email python_神器:让python发送电子邮件像傻瓜一样简单

    用过python其他邮件模块老铁们吼一声--tm是给人用的吗? py3_email超简单,超易用. 以近乎傻瓜式的方式发送邮件 到底有多简单,请看:添加标题: add_title() 添加文本: ad ...

  4. python自建邮件服务器,9行自定义函数教你用Python发送电子邮件!

    作者 l 刘顺祥 来源 l 数据分析1480 前言 大概是在两三个月前,陆续有几位在职朋友问我如何使用Python发送邮件,说心里话这方面的操作在我之前的工作履历中真的没有碰到,所以我没有很好地帮助他 ...

  5. 【私人订制Python模块库】Pyemail:更方便快捷地发送电子邮件

    文章目录 一.前言背景 二.个人首秀模块 三.如何打包模块 四.实际运用例子 一.前言背景 前几天学习了smtplib和email模块,Get了新技能--如何用Python发送电子邮件,还能发送超文本 ...

  6. 在Python中使用SMTP发送电子邮件

    Python中有内置的smtplib模块,完成一封邮件的发送,需要做很多准备工作.第三方的py_smtp这个包也是基于smtplib的,在Python中使用py_smtp发送电子邮件非常方便,只要填写 ...

  7. python中带附件发送电子邮件_python发送带附件邮件

    Python SMTP发送邮件 SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式. py ...

  8. 邮件发送时间怎么修改 python_使用python通过电子邮件发送日期时间

    我试图使用python脚本解析电子邮件的日期时间. 在我打开邮件时,邮件日期值如下所示... 1 2 3 4from: abcd@xyz.com to: def@xyz.com date: Tue, ...

  9. python发送excel文件_如何在Python中使用Excel文件(xlsx)附件发送电子邮件

    我需要发送一封带有Excel附件的电子邮件 我的代码如下,可以发送电子邮件 但是当我收到邮件时,附件文件不是Excel文件~~ 看来我附加的格式不对~~~ 我添加了不同的电子邮件地址来接收此电子邮件 ...

最新文章

  1. Keras Theano 输出中间层结果
  2. 现代操作系统: 第六章 死锁
  3. mongodb学习(六)索引
  4. VIM中常用的替换模式总结
  5. 离散数学实验题目-图
  6. 【Linux系统编程】文件IO操作
  7. Java13的API_JAVA基础--JAVA API常见对象(其他API)13
  8. 高效利用无标注数据:自监督学习简述
  9. Pytorch中参数和模型的保存与读取
  10. 微信亲戚备注分组名称_微信新功能上线!群聊名称可备注,仅自己可见
  11. matlab光束,matlab仿真光束的传输特性
  12. Quartz和OpenGL绘图基本概念
  13. java程序开发的简历_Java程序开发工作简历
  14. 计算机酒店管理论文,计算机专业酒店管理系统毕业论文.doc
  15. 机房资产管理系统linux,资产管理平台设备技术指标.doc
  16. 用python判断火车票座位_Python3 实现火车票查询工具
  17. 【Python】reset_index函数
  18. 百度获取天气预报接口
  19. 常微分方程组之龙格-库塔法
  20. java-IO流(2)-字节流和字符流的介绍

热门文章

  1. 阿里P7大牛亲自教你!BAT这种大厂履历意味着什么?积累总结
  2. uoj#388. 【UNR #3】配对树(线段树合并)
  3. node中的Stream-Readable和Writeable解读
  4. PHP代码20个实用技巧(转)
  5. 关于自动布局更新约束方法的总结
  6. php文件操作基本使用方法
  7. 优秀的SharePoint 2013开发工具有哪些(二)
  8. Delphi小技巧杂记
  9. K8S仪表板Service unavailable故障的解决办法
  10. java基础-BigDecimal类常用方法介绍