如何用Python实现电子邮件的自动化

在本文中,我们将概述如何编写一个Python脚本,该脚本可以下载一组特定的公共数据,然后将其上传到电
首页 新闻资讯 行业资讯 如何用Python实现电子邮件的自动化

前言

用Python自动化日常任务很容易。通过api和库的结合,您可以轻松地设置系统来抓取网站、发送电子邮件、管理数据和分析。

在本文中,我们将概述如何编写一个Python脚本,该脚本可以下载一组特定的公共数据,然后将其上传到电子邮件中,并将其发送给任何需要的人。

这将使您熟悉使用Python请求库和Gmail API。因此,如果您希望将来使用Python自动处理电子邮件,这是一个很好的学习起点。

用Python下载文件

对于第一步,我们将需要使用HTTP请求实际下载数据文件。

在本例中,我们将要下载的文件甚至在下面的链接中有一个简单的端点。因此,您不需要使用Selenium这样的库来尝试单击下载按钮。通常,如果有一个URL,那么使用链接下载就非常容易。

https://data.medicaid.gov/api/views/u72p-j37s/rows.json?accessType=DOWNLOAD

这个文件提供关于医疗补助和个人登记的信息。这对医疗保健提供者来说是有价值的,他们可以将其与内部数据联系起来,帮助更好地了解他们的市场。

为了下载它,我们将使用函数requests.get()。这将允许我们使用HTTP请求将数据拉到我们指定的URL。

例如,你可以看看下面的脚本:

复制

# Part 1: Fetch the data.  # Get the webpage, store it in a Response object and assign the text # About: https://requests.readthedocs.io/en/master/api/#requests.Response  # This URL contains the .csv download of # 'https://catalog.data.gov/dataset/' \ #  'share-of-medicaid-enrollees-in-managed-care' # used to send to the destination e-mail.  csvFileURL = 'https://data.medicaid.gov/api/' \  'views/u72p-j37s/rows. csv?accessType=DOWNLOAD'csvFileRequest = requests.get(csvFileURL)csvFile = csvFileRequest.content
  • 1.

  • 2.

  • 3.

  • 4.

  • 5.

  • 6.

  • 7.

  • 8.

  • 9.

  • 10.

  • 11.

  • 12.

它短小精悍,并将返回CSV作为您现在设置为变量的请求的一部分。我们稍后在创建电子邮件时将使用这个。但是接下来,我们需要设置Gmail  API的凭据。

设置您的Gmail API

谷歌使您非常容易地设置api。您可以转到谷歌API控制台。从这里,您可以选择ENABLE API和服务,然后搜索Gmail API。

API控制台如下图所示。

 

如何用Python实现电子邮件的自动化

你可以输入Gmail,它应该是唯一出现的。

 

如何用Python实现电子邮件的自动化

然后您可以选择Gmail API,它旁边会有一个ENABLE按钮。

 

如何用Python实现电子邮件的自动化

一旦您在Gmail API上单击ENABLE,您就可以下载您的凭证或者使用API密钥和密钥。

我们的代码将使用JSON下载,但如果您愿意,可以将其转换为pickle。

 

如何用Python实现电子邮件的自动化

有了这些设置,我们现在可以开始建立你的功能设置,然后自动发送你的电子邮件。

使用Gmail API 发送邮件

现在我们已经找到了一种获取数据的方法,我们需要弄清楚如何发送电子邮件。

为了做到这一点,我们将使用电子邮件库。这个库可以让我们设置电子邮件的各个部分:发件人、收件人、主题等。

我们在电子邮件中使用MIMEBase类来实现这一点,这使得设置正确的数据点变得很容易,并且为将来使用的Gmail API提供了一个简单的类。

使用MIMEBase类真的很简单,因为你可以创建一个新的类,然后引用很多需要的组件,比如:

复制

message[‘from’] = test@gmail.com
  • 1.

您可以看到我们在下面设置这些参数的整个函数。

复制

# Function required for Part 2: Send e-mail with Google API. # a) Create the message  def create_message(sender, to, subject, csv):   #message = MIMEMultipart()       message = MIMEMultipart()   message['from'] = sender   message['to'] = to     message['subject'] = subject  # Send the time it was updated as the body of the e-mail   dt_object = datetime.utcnow() - timedelta(hours = 7)   msg = MIMEText('Hi! Your file was updated.' \    '\nTime of update: ' + dt_object.strftime('%m/%d/%Y, %I:%M:%S %p') \    + ' (Los Angeles Time)')   message.attach(msg)  # Attach the .csv file   record = MIMEBase('application', 'octet-stream')   # print(csv)   record.set_payload(csv)   encoders.encode_base64(record)   record.add_header('Content-Disposition', 'attachment', filename='medicare.csv')   message.attach(record)  # Return the message   raw = base64.urlsafe_b64encode(message.as_bytes())   raw = raw.decode()   return {'raw': raw}
  • 1.

  • 2.

  • 3.

  • 4.

  • 5.

  • 6.

  • 7.

  • 8.

  • 9.

  • 10.

  • 11.

  • 12.

  • 13.

  • 14.

  • 15.

  • 16.

  • 17.

  • 18.

  • 19.

  • 20.

  • 21.

  • 22.

  • 23.

  • 24.

  • 25.

  • 26.

  • 27.

您将注意到在最后,我们使用了函数urlsafe_b64encode。这将把消息设置为字节。这将用于轻松地将电子邮件数据传输到Gmail  API。所以它很容易传递。

现在是时候发送你的第一封自动邮件了。现在您已经设置了Gmail API凭据,我们可以发送第一封电子邮件了。我们将使用使用Gmail  API和凭据设置的服务变量。这如下面的函数send_message所示。

复制

#b) Send the message  def send_message(service, user_id, message):       try:    message = service.users().messages(). \        send(userId=user_id, body=message).execute()        print('Message Id: %s' % message['id'])        return message    except Exception as e:       print('An error occurred: %s' % e)       return None
  • 1.

  • 2.

  • 3.

  • 4.

  • 5.

  • 6.

  • 7.

  • 8.

  • 9.

  • 10.

从这里开始,我们需要做的就是传递消息并执行。至此,我们已经发送了第一封电子邮件。