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/