使用Python发送电子邮件

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/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/396321.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

此blog不更了

1转载于:https://www.cnblogs.com/ybai62868/p/5384097.html

Unable to find required classes (javax.activation.DataHandler and javax.mail.internet.MimeMultipart)

在接触WebService时值得收藏的一篇文章: 在调试Axis1.4访问WebService服务时,出现以下错误: Unable to find required classes (javax.activation.DataHandler and javax.mail.internet.MimeMultipart) 有错误找到错误原因以及发现值得收藏的…

java遍历树结构数据_Java数据结构——二叉树的遍历(汇总)

二叉树的遍历分为深度优先遍历(DFS)和广度优先遍历(BFS)DFS遍历主要有:前序遍历中序遍历后序遍历一、递归实现DFSNode.java:public class Node {private Object data;Node richild;Node lechild;public Object getData() {return data;}public void setData(Object …

vue 移动端头像裁剪_使用vue-cropper裁剪正方形上传头像-阿里云开发者社区

引用方式在组件内使用import { VueCropper } from vue-croppercomponents: {VueCropper,},main.js里面使用import VueCropper from vue-cropperVue.use(VueCropper)基本使用方法ref"cropper":img"option.img":autoCrop"true":fixedNumber"[…

规则引擎 设计 git_引擎盖下的Git

规则引擎 设计 gitby Wassim Chegham由Wassim Chegham 引擎盖下的Git (Git under the hood) Let’s explore some common Git commands, and dive into its internals to see what Git does when you run them.让我们探索一些常见的Git命令,并深入了解其内部&#…

练习题之死锁

public class PrintMain {public static String obj1"obj1";public static String obj2"obj2";public static void main(String[] args) {new Thread(new Runnable() {public void run() {System.out.println(new Date().toString "LockA开始执行&qu…

启用或禁用对 Exchange Server 中的邮箱的 POP3 或 IMAP4 访问

https://docs.microsoft.com/zh-cn/Exchange/clients/pop3-and-imap4/configure-mailbox-access?viewexchserver-2019 记录下转载于:https://www.cnblogs.com/amoy9812/p/9875426.html

java有什么压力_编程语言的心智负担!你学编程得有多大的压力快来测试一下...

很多编程语言对比的文章,总喜欢比较各种编程语言的性能、语法、IO模型。本文将从心智负担这个角度去比较下不同的编程语言和技术。内存越界如:C语言、C(C with class)C/C可以直接操作内存,但编程必须要面对内存越界问题。发生内存越界后&…

什么叫有效物理网卡_如何区分虚拟网卡和物理网卡?-阿里云开发者社区

一、什么是物理网卡和虚拟网卡?图示如下:红色部分包含VMWare的为虚拟网卡。通常,我们部署VMWare虚拟机、VMSphere虚拟集群、XenCenter虚拟集群是都会涉及虚拟网卡。二、辨别物理网卡和虚拟网卡的应用场景场景一:一般部署虚拟集群的…

算法复杂度的表示法_用简单的英语算法:时间复杂度和Big-O表示法

算法复杂度的表示法by Michael Olorunnisola通过Michael Olorunnisola 用简单的英语算法:时间复杂度和Big-O表示法 (Algorithms in plain English: time complexity and Big-O notation) Every good developer has time on their mind. They want to give their us…

Android Studio 开始运行错误

/********************************************************************************* Android Studio 开始运行错误* 说明:* 打开Android Studio就抛出这个错误。* * 2017-4-1 深圳 南…

IOS 计步器

这篇博客介绍的是当前比较流行的“计步器”-只是简单的知识点 计步器的实现在IOS8开始进行了改变。 但是我会对之前之后的都进行简单介绍。 IOS 8 - // // ViewController.m // CX 计步器 // // Created by ma c on 16/4/12. // Copyright © 2016年 bjsxt. All rights…

vue学习之二ECMAScript6标准

一、ECMAScript6标准简述 ECMAScript 6.0(以下简称 ES6)是 JavaScript 语言的下一代标准,已经在 2015 年 6 月正式发布了。它的目标,是使得 JavaScript 语言可以用来编写复杂的大型应用程序,成为企业级开发语言。 1.1E…

抖音吸粉_抖音吸粉5大实用方法首次分享!轻松实现粉丝10000+

抖音,是一款可以拍短视频的音乐创意短视频社交软件,该软件于2016年9月上线,是一个专注年轻人音乐短视频社区。用户可以通过这款软件选择歌曲,拍摄音乐短视频,形成自己的作品。抖音APP仅推出半年,用户量就突…

mapper mysql 主键_实现通用mapper主键策略兼容mysql和oracle

【原创文章,转载请注明原文章地址,谢谢!】1.直接用官方提供的注解方法是无法达到兼容效果的2.跟踪源码看看是否有其他方法3.这里有个genSql,可以看一下这个类4.创建一个自定义的处理类实现GenSql(代码中是我实际项目中用到的策略&…

权限分配界面 纯手工 仅用到bootstrap的架构 以及 c标签

<div class"form-group"> <div class"row"> <label class"col-sm-2 control-label">配置权限</label> <div class"col-sm-10"> <c:forEach var"m" items…

数据管理与数据库 大学课程_根据数据显示的50种最佳免费在线大学课程

数据管理与数据库 大学课程When I launched Class Central back in November 2011, there were around 18 or so free online courses, and almost all of them were from Stanford.当我在2011年11月推出Class Central时&#xff0c;大约有18项免费在线课程&#xff0c;几乎所有…

每天一个linux命令(12):more命令

more命令&#xff0c;功能类似 cat &#xff0c;cat命令是整个文件的内容从上到下显示在屏幕上。 more会以一页一页的显示方便使用者逐页阅读&#xff0c;而最基本的指令就是按空白键&#xff08;space&#xff09;就往下一页显示&#xff0c;按 b 键就会往回&#xff08;back&…

java 面试题 由浅入深_面试官由浅入深的面试套路

阅读文本大概需要3分钟。从上图看来面试官面试是有套路的&#xff0c;一不小心就一直被套路。0x01&#xff1a;Thread面试官&#xff1a;创建线程有哪几种方式&#xff1f;应聘者&#xff1a;继承Thread类、实现Runable接口、使用j.u.c中的线程池面试官&#xff1a;继承Thread类…

怎么用centos7运行c语言程序_centos如何编译c语言代码

centos如何编译c语言代码,文件,选项,作用,链接,程序 centos如何编译c语言代码 易采站长站,站长之家为您整理了centos如何编译c语言代码的相关内容。 编译c,c++代码 安装gcc 1、使用如下命令查询 centos 官方gcc的所有包:yum -list gcc* 可安装的软件包gcc.x86_64gcc-c++.x86…