首页 > 解决方案 > 使用 Python Gmail API 在 Latex 中发送 Gmail

问题描述

我在 Python 中使用 Gmail API 并尝试发送包含 Latex 的电子邮件。我知道
已经可以使用 Latex 发送 gmail 消息的扩展程序和附加组件。
我的错误不在 python 代码中,而是在电子邮件中。该电子邮件不包含正文和一个
显示“noname”的附件,所有其他字段均已正确填写。我没有在网上找到任何与我的问题相似的东西。
据我了解,我可能使用了不正确的 mime 类型,或者 Gmail 不了解我在
电子邮件正文中输入的内容。

1. 在使用任何乳胶之前,我已验证电子邮件确实以纯文本形式发送。
2. 已验证的接收者确实收到了消息
3. 使用乳胶发送和接收的已验证消息,但有“
4. 尝试过 text/html、application/x-latex、text/plain 但 html 和 latex 不起作用。
5. json 和凭证文件是最新的
6. 我试过 sympy 但也不是很有用:

'''
    func = sp.Function('func')
    x = sp.Symbol('x')
    func = sp.sin(x)
    message_text = func
'''

这是我的代码的片段:

为电子邮件创建一条消息。

Args:发件人:发件人的电子邮件地址。
to:收件人的电子邮件地址。
主题:电子邮件的主题。
message_text:电子邮件的文本。

返回:
包含 base64url 编码的电子邮件对象的对象。

'''
def create_message(sender, to, subject, message_text):
  message_text = "$x^2"
  #message = MIMEText(message_text)
  message = MIMEText(message_text, 'application/x-latex')
  message['to'] = to
  message['from'] = sender
  message['subject'] = subject
  return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}#changed as_string() to as_string().encode()).decode
'''

发送电子邮件。

args: service: 授权的 Gmail API 服务实例。user_id:用户的电子邮件地址。特殊值“me”可用于表示经过身份验证的用户。消息:要发送的消息。

返回:已发送消息。

 '''
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 errors.HttpError as error:
    print ('An error occurred: %s' % error)

'''



带有附件“noname”的 gmail 电子邮件

标签: python-3.xgmailgmail-apimime-typesmime

解决方案


解释

根据文档,您的 MIME 类型application/x-latex被 API 解释为附件 MIME 类型。

在上面的链接中,您可以看到 google 识别的内容。请记住,它提到对于那些未被识别的 App Engine 将分配 MIME 类型application/octet-stream

这就是为什么当您在未指定 MIME 类型的情况下发送消息时,用户将$x^2在正文中收到一封电子邮件,而当您指定使用 Latex 时,用户会收到一个未指定名称但$x^2在其内容中的附件。


推荐阅读