使用Python发送电子邮件
by Arjun Krishna Babu
通過(guò)Arjun Krishna Babu
如何使用Python發(fā)送電子郵件 (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.
作為一項(xiàng)學(xué)習(xí)練習(xí),我最近研究了Python 3,以了解如何解雇大量電子郵件。 在生產(chǎn)環(huán)境中可能會(huì)有更直接的方法來(lái)執(zhí)行此操作,但是以下方法對(duì)我來(lái)說(shuō)效果很好。
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.
因此,這是一個(gè)場(chǎng)景:您擁有一堆聯(lián)系人的姓名和電子郵件地址。 您想向每個(gè)聯(lián)系人發(fā)送消息,同時(shí)在消息頂部添加“ 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.
為簡(jiǎn)單起見(jiàn),您可以將聯(lián)系方式存儲(chǔ)在文件中,而不是數(shù)據(jù)庫(kù)中。 您也可以將要發(fā)送的消息模板存儲(chǔ)在文件中。
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模塊基本上就是您發(fā)送簡(jiǎn)單電子郵件所需要的,而沒(méi)有任何主題行或此類附加信息。 但是對(duì)于真實(shí)的電子郵件,您確實(shí)需要主題行和大量信息,甚至是圖片和附件。
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 電子郵件包的來(lái)源。請(qǐng)記住,不可能僅使用email包發(fā)送電子郵件。 您需要同時(shí)使用email和smtplib 。
Be sure to check out the comprehensive official documentation for both of these.
請(qǐng)務(wù)必查看這兩個(gè)文件的綜合官方文檔。
Here are four basic steps for sending emails using Python:
這是使用Python發(fā)送電子郵件的四個(gè)基本步驟:
Create the MIMEMultipart message object and load it with appropriate headers for From, To, and Subject fields.
創(chuàng)建MIMEMultipart消息對(duì)象,并使用From , To和Subject字段的適當(dāng)標(biāo)題加載它。
Now let me walk you through the whole process.
現(xiàn)在,讓我引導(dǎo)您完成整個(gè)過(guò)程。
Let’s say you have a contacts file mycontacts.txt as follows:
假設(shè)您有一個(gè)聯(lián)系人文件mycontacts.txt ,如下所示:
user@computer ~ $ cat mycontacts.txt john johndoe@example.com katie katie2016@example.comEach 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.
每行代表一個(gè)聯(lián)系人。 我們的名字后面是電子郵件地址。 我將所有內(nèi)容都以小寫(xiě)形式存儲(chǔ)。 如有必要,我將其留給編程邏輯以將任何字段轉(zhuǎn)換為大寫(xiě)或句子大小寫(xiě)。 所有這些在Python中都非常容易。
Next, we have the message template file message.txt.
接下來(lái),我們有消息模板文件message.txt 。
user@computer ~ $ cat message.txt Dear ${PERSON_NAME}, This is a test message. Have a great weekend! Yours TrulyNotice 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}將被替換為該人的實(shí)際姓名,您很快就會(huì)看到。
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.
現(xiàn)在讓我們從Python代碼開(kāi)始。 首先,我們需要從mycontacts.txt文件中讀取聯(lián)系人。 我們不妨將此位概括為自己的功能。
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.
函數(shù)get_contacts()以文件名作為參數(shù)。 它將打開(kāi)文件,閱讀每一行(即每個(gè)聯(lián)系人),將其拆分為姓名和電子郵件,然后將它們附加到兩個(gè)單獨(dú)的列表中。 最后,兩個(gè)列表從函數(shù)中返回。
We also need a function to read in a template file (like message.txt) and return a Template object made from its contents.
我們還需要一個(gè)函數(shù)來(lái)讀取模板文件(例如message.txt )并返回由其內(nèi)容構(gòu)成的Template對(duì)象。
Just like the previous function, this one takes a filename as its argument.
就像上一個(gè)函數(shù)一樣,該函數(shù)將文件名作為參數(shù)。
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.
要發(fā)送電子郵件,您需要使用SMTP(簡(jiǎn)單郵件傳輸協(xié)議) 。 如前所述,Python提供了處理此任務(wù)的庫(kù)。
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:
在上面的代碼片段中,您要導(dǎo)入smtplib ,然后創(chuàng)建一個(gè)封裝SMTP連接的SMTP實(shí)例 。 它以主機(jī)地址和端口號(hào)作為參數(shù),這兩者完全取決于特定電子郵件服務(wù)提供商的SMPT設(shè)置。 例如,在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.
您應(yīng)該使用特定電子郵件服務(wù)提供商的主機(jī)地址和端口號(hào)才能正常工作。
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是兩個(gè)變量,用于保存您要使用的帳戶的完整電子郵件地址和密碼。
Now would be a good time to fetch the contact information and the message templates using the functions we defined above.
現(xiàn)在將是使用我們上面定義的功能來(lái)獲取聯(lián)系信息和消息模板的好時(shí)機(jī)。
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.
現(xiàn)在,對(duì)于每個(gè)聯(lián)系人,讓我們分別發(fā)送郵件。
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.
對(duì)于每個(gè)name和email (來(lái)自聯(lián)系人文件),您將創(chuàng)建一個(gè)MIMEMultipart對(duì)象,將From , To , Subject內(nèi)容類型標(biāo)題設(shè)置為關(guān)鍵字字典,然后將郵件正文作為純文本附加到MIMEMultipart對(duì)象。 您可能需要閱讀文檔,以了解有關(guān)可以嘗試的其他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中的模板機(jī)制將${PERSON_NAME}替換${PERSON_NAME}從聯(lián)系人文件中提取的實(shí)際名稱。
In this particular example I’m deleting the MIMEMultipart object and re-creating it each time you iterate through the loop.
在此特定示例中,我將刪除MIMEMultipart對(duì)象,并在每次迭代循環(huán)時(shí)重新創(chuàng)建它。
Once that is done, you can send the message using the handy send_message() function of the SMTP object you created earlier.
完成后,您可以使用之前創(chuàng)建的SMTP對(duì)象的便捷send_message()函數(shù)發(fā)送郵件。
Here’s the full code:
這是完整的代碼:
There you go! I believe the code is now fairly clear.
你去! 我相信代碼現(xiàn)在已經(jīng)很清楚了。
Feel free to copy and tweak it as necessary.
隨時(shí)復(fù)制和調(diào)整它。
Apart from the official Python docs, I would also like to mention this resource which helped me a lot.
除了官方的Python文檔外,我還想提到這個(gè)資源 ,它對(duì)我有很大幫助。
Happy coding :)
快樂(lè)的編碼:)
I originally published this article here. If you liked this article, please hit the small heart below. Thanks!
我最初是在這里發(fā)表這篇文章的。 如果您喜歡這篇文章,請(qǐng)打以下小心臟。 謝謝!
翻譯自: https://www.freecodecamp.org/news/send-emails-using-code-4fcea9df63f/
總結(jié)
以上是生活随笔為你收集整理的使用Python发送电子邮件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 梦到鱼跳水是什么意思
- 下一篇: 梦到游泳是怎么回事