使用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.pswp.cn/news/396321.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/396321.shtml
英文地址,請注明出處:http://en.pswp.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…