Google apps script Gmail的谷歌应用程序脚本-收件箱中的坏邮件
我开发了一个Gmail插件。 在这方面,我将得到电子邮件列表,从,到,抄送和密件抄送的帮助下,类。 比如电子邮件中的, 如需发送电子邮件, 文档中指出,它将以字符串形式返回电子邮件,但没有明确提及该字符串的格式。 有时我会使用Google apps script Gmail的谷歌应用程序脚本-收件箱中的坏邮件,google-apps-script,Google Apps Script,我开发了一个Gmail插件。 在这方面,我将得到电子邮件列表,从,到,抄送和密件抄送的帮助下,类。 比如电子邮件中的, 如需发送电子邮件, 文档中指出,它将以字符串形式返回电子邮件,但没有明确提及该字符串的格式。 有时我会使用帐户名的格式 有时采用格式,有时仅提供姓名,而不提供收件人的电子邮件ID。 有时,它还包括电子邮件上的双引号,如帐户名称 有人能告诉我,有没有一种方法可以使用谷歌应用程序脚本从Gmail中分别获得准确的电子邮件地址和姓名? 或者建议一些方法来解析来自gmail Messag
帐户名的格式
有时采用
格式,有时仅提供姓名,而不提供收件人的电子邮件ID。
有时,它还包括电子邮件上的双引号,如帐户名称
有人能告诉我,有没有一种方法可以使用谷歌应用程序脚本从Gmail中分别获得准确的电子邮件地址和姓名?
或者建议一些方法来解析来自gmail Message类的电子邮件,并分别获取电子邮件地址和名称我在gmail api网站上找到了一些方法,如果您最终使用这些代码,这些方法可能会被使用。虽然代码是用python编写的,因此可能无法在google应用程序脚本上运行,但使用google应用程序脚本的唯一原因是为了实现这些结果。你还必须知道在使用它时你在做什么(如果你想使用谷歌应用程序脚本,试着制作一个gmail应用程序模板,然后到这里学习基础知识,并在这里获取更多文档) 将
CLIENTSECRETS\u LOCATION
值替换为client\u secrets.json
文件的位置
import logging
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
from apiclient.discovery import build
# ...
# Path to client_secrets.json which should contain a JSON document such as:
# {
# "web": {
# "client_id": "[[YOUR_CLIENT_ID]]",
# "client_secret": "[[YOUR_CLIENT_SECRET]]",
# "redirect_uris": [],
# "auth_uri": "https://accounts.google.com/o/oauth2/auth",
# "token_uri": "https://accounts.google.com/o/oauth2/token"
# }
# }
CLIENTSECRETS_LOCATION = '<PATH/TO/CLIENT_SECRETS.JSON>'
REDIRECT_URI = '<YOUR_REGISTERED_REDIRECT_URI>'
SCOPES = [
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
# Add other requested scopes.
]
class GetCredentialsException(Exception):
"""Error raised when an error occurred while retrieving credentials.
Attributes:
authorization_url: Authorization URL to redirect the user to in order to
request offline access.
"""
def __init__(self, authorization_url):
"""Construct a GetCredentialsException."""
self.authorization_url = authorization_url
class CodeExchangeException(GetCredentialsException):
"""Error raised when a code exchange has failed."""
class NoRefreshTokenException(GetCredentialsException):
"""Error raised when no refresh token has been found."""
class NoUserIdException(Exception):
"""Error raised when no user ID could be retrieved."""
def get_stored_credentials(user_id):
"""Retrieved stored credentials for the provided user ID.
Args:
user_id: User's ID.
Returns:
Stored oauth2client.client.OAuth2Credentials if found, None otherwise.
Raises:
NotImplemented: This function has not been implemented.
"""
# TODO: Implement this function to work with your database.
# To instantiate an OAuth2Credentials instance from a Json
# representation, use the oauth2client.client.Credentials.new_from_json
# class method.
raise NotImplementedError()
def store_credentials(user_id, credentials):
"""Store OAuth 2.0 credentials in the application's database.
This function stores the provided OAuth 2.0 credentials using the user ID as
key.
Args:
user_id: User's ID.
credentials: OAuth 2.0 credentials to store.
Raises:
NotImplemented: This function has not been implemented.
"""
# TODO: Implement this function to work with your database.
# To retrieve a Json representation of the credentials instance, call the
# credentials.to_json() method.
raise NotImplementedError()
def exchange_code(authorization_code):
"""Exchange an authorization code for OAuth 2.0 credentials.
Args:
authorization_code: Authorization code to exchange for OAuth 2.0
credentials.
Returns:
oauth2client.client.OAuth2Credentials instance.
Raises:
CodeExchangeException: an error occurred.
"""
flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
flow.redirect_uri = REDIRECT_URI
try:
credentials = flow.step2_exchange(authorization_code)
return credentials
except FlowExchangeError, error:
logging.error('An error occurred: %s', error)
raise CodeExchangeException(None)
def get_user_info(credentials):
"""Send a request to the UserInfo API to retrieve the user's information.
Args:
credentials: oauth2client.client.OAuth2Credentials instance to authorize the
request.
Returns:
User information as a dict.
"""
user_info_service = build(
serviceName='oauth2', version='v2',
http=credentials.authorize(httplib2.Http()))
user_info = None
try:
user_info = user_info_service.userinfo().get().execute()
except errors.HttpError, e:
logging.error('An error occurred: %s', e)
if user_info and user_info.get('id'):
return user_info
else:
raise NoUserIdException()
def get_authorization_url(email_address, state):
"""Retrieve the authorization URL.
Args:
email_address: User's e-mail address.
state: State for the authorization URL.
Returns:
Authorization URL to redirect the user to.
"""
flow = flow_from_clientsecrets(CLIENTSECRETS_LOCATION, ' '.join(SCOPES))
flow.params['access_type'] = 'offline'
flow.params['approval_prompt'] = 'force'
flow.params['user_id'] = email_address
flow.params['state'] = state
return flow.step1_get_authorize_url(REDIRECT_URI)
def get_credentials(authorization_code, state):
"""Retrieve credentials using the provided authorization code.
This function exchanges the authorization code for an access token and queries
the UserInfo API to retrieve the user's e-mail address.
If a refresh token has been retrieved along with an access token, it is stored
in the application database using the user's e-mail address as key.
If no refresh token has been retrieved, the function checks in the application
database for one and returns it if found or raises a NoRefreshTokenException
with the authorization URL to redirect the user to.
Args:
authorization_code: Authorization code to use to retrieve an access token.
state: State to set to the authorization URL in case of error.
Returns:
oauth2client.client.OAuth2Credentials instance containing an access and
refresh token.
Raises:
CodeExchangeError: Could not exchange the authorization code.
NoRefreshTokenException: No refresh token could be retrieved from the
available sources.
"""
email_address = ''
try:
credentials = exchange_code(authorization_code)
user_info = get_user_info(credentials)
email_address = user_info.get('email')
user_id = user_info.get('id')
if credentials.refresh_token is not None:
store_credentials(user_id, credentials)
return credentials
else:
credentials = get_stored_credentials(user_id)
if credentials and credentials.refresh_token is not None:
return credentials
except CodeExchangeException, error:
logging.error('An error occurred during code exchange.')
# Drive apps should try to retrieve the user and credentials for the current
# session.
# If none is available, redirect the user to the authorization URL.
error.authorization_url = get_authorization_url(email_address, state)
raise error
except NoUserIdException:
logging.error('No user ID could be retrieved.')
# No refresh token has been retrieved.
authorization_url = get_authorization_url(email_address, state)
raise NoRefreshTokenException(authorization_url)
导入日志
从oauth2client.client导入流\u从\u clientsecrets
从oauth2client.client导入FlowExchangeError
从apiclient.discovery导入生成
# ...
#指向client_secrets.json的路径,其中应包含json文档,例如:
# {
#“网络”:{
#“客户id”:“[[您的客户id]]”,
#“客户机密”:“[[您的客户机密]”,
#“重定向URI”:[],
#“auth_uri”:https://accounts.google.com/o/oauth2/auth",
#“令牌uri”:https://accounts.google.com/o/oauth2/token"
# }
# }
CLIENTSECRETS\u位置=“”
重定向_URI=''
作用域=[
'https://www.googleapis.com/auth/gmail.readonly',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
#添加其他请求的作用域。
]
类GetCredentialsException(异常):
“”检索凭据时出错时引发的错误。
属性:
授权url:将用户重定向到的授权url,以便
请求脱机访问。
"""
定义初始化(自授权url):
“”“构造GetCredentialsException。”“”
self.authorization\u url=授权\u url
类CodeExchangeException(GetCredentialsException):
“”“代码交换失败时引发错误。”“”
类NoRefreshTokenException(GetCredentialsException):
“”“未找到刷新令牌时引发错误。”“”
类NoUserIdexException(异常):
“”“无法检索用户ID时引发错误。”“”
def get_stored_凭证(用户id):
“”“检索到所提供用户ID的存储凭据。
Args:
用户id:用户的id。
返回:
存储的oauth2client.client.OAuth2Credentials如果找到,则不存在。
提出:
NotImplemented:此函数尚未实现。
"""
#TODO:实现此功能以使用数据库。
#从Json实例化OAuth2Credentials实例
#表示中,使用oauth2client.client.Credentials.new\u from\u json
#类方法。
引发未实现的错误()
def存储凭据(用户id、凭据):
“”“在应用程序的数据库中存储OAuth 2.0凭据。
此函数使用用户ID存储提供的OAuth 2.0凭据,如下所示:
钥匙
Args:
用户id:用户的id。
凭据:要存储的OAuth 2.0凭据。
提出:
NotImplemented:此函数尚未实现。
"""
#TODO:实现此功能以使用数据库。
#要检索凭据实例的Json表示,请调用
#credentials.to_json()方法。
引发未实现的错误()
def交换代码(授权代码):
“”“为OAuth 2.0凭据交换授权代码。”。
Args:
授权代码:用于交换OAuth 2.0的授权代码
资格证书
返回:
oauth2client.client.OAuth2Credentials实例。
提出:
CodeExchangeException:发生错误。
"""
flow=来自clientsecrets的流(clientsecrets位置“”。加入(作用域))
flow.redirect_uri=重定向_uri
尝试:
凭证=流程。步骤2\u交换(授权\u代码)
返回凭证
除FlowExchangeError外,错误:
logging.error('发生错误:%s',错误)
引发代码交换异常(无)
def获取用户信息(凭据):
“”“向UserInfo API发送请求以检索用户信息。
Args:
凭据:oauth2client.client.OAuth2Credentials实例以授权
要求
返回:
用户信息作为命令。
"""
用户信息服务=构建(
serviceName='oauth2',version='v2',
http=credentials.authorize(httplib2.http())
用户信息=无
尝试:
user\u info=user\u info\u service.userinfo().get().execute()
除了errors.HttpError,e:
logging.error('发生错误:%s',e)
如果用户信息和用户信息获取('id'):
返回用户信息
其他:
提出NoUserIdexException()
def获取授权url(电子邮件地址、状态):
“”“检索授权URL。
Args:
电子邮件地址:用户的电子邮件地址。
状态:授权URL的状态。
返回:
将用户重定向到的授权URL。
"""
flow=来自clientsecrets的流(clientsecrets位置“”。加入(作用域))
flow.params['access_type']='offline'
flow.params['approval\u prompt']='force'
flow.params['user\u id']=电子邮件地址
flow.params['state']=状态
返回流。步骤1\u获取\u授权\u url(重定向\u URI)
def get_凭证(授权代码、状态):
“取回克雷登