【问题标题】:Simple way to send an html/text email using sendgrid & python?使用 sendgrid 和 python 发送 html/文本电子邮件的简单方法?
【发布时间】:2017-08-31 14:11:03
【问题描述】:

我正在尝试使用 sendgrid 从我的 Python 应用程序发送电子邮件。

使用邮件助手和以下语法可以正常发送:

sgmessage = mail.Mail(from_email, message.subject, to_email, content)
sg.client.mail.send.post(request_body=sgmessage.get())

但我找不到发送包含文本和 html 版本的多部分/替代内容类型的电子邮件的方法?

我尝试过这样的事情:

sgmessage = mail.Mail(from_email, message.subject, to_email)
sgmessage.add_content(content)
sgmessage.add_content(htmlcontent)

但是当我尝试发送时,这给了我错误的请求。

有人可以指点我实现此目的的文档或其他提示吗?

还有附件——我找不到那个方便的邮件助手的文档,它可以帮助我在我的代码中添加附件功能。

【问题讨论】:

    标签: python email sendgrid


    【解决方案1】:
    import os
    
    from sendgrid import SendGridAPIClient
    from sendgrid.helpers.mail import Mail
    
    
    def send_email(emails, notification_text, subject):
        """Send Emails
    
        Send email to the mail ids
    
        :param emails: emails of the user
        :type emails: list
        :param notification_text: notification text
        :type notification_text: str
        :param request_link: link to the requet
        :type request_link: str
        :param subject: subject of the email
        :type subject: str
    
        :rtype: str
        """
        html_content = '<strong>' + notification_text + '</strong>'
        emails = emails
        message = Mail(
            from_email='yourSendGridVerifiedEmail',
            to_emails=emails,
            subject=subject,
            html_content=html_content)
        try:
            sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY'))
            sg.send(message)
            return "Email Sent"
        except Exception as e:
            return e.message
    

    【讨论】:

      【解决方案2】:

      邮件助手源https://github.com/sendgrid/sendgrid-python/blob/master/sendgrid/helpers/mail/mail.py

      mail_html = Content(type_='text/html', value='<h1>Test Mail</h1><p>This is a test email message.</p>')
      mail_txt = Content(type_='text/plain', value='This is a test email message.')
      mail = Mail(mail_from, mail_subject, mail_to, mail_html)
      mail.add_content(mail_txt)
      response = sg.client.mail.send.post(request_body=mail.get())
      

      示例链接仍然是 404 的。

      【讨论】:

        【解决方案3】:

        你看过SendGrid Python Library吗? basic example 仅显示一种内容类型,但 "kitchen sink" 示例显示设置两种内容。

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-13
        • 1970-01-01
        • 1970-01-01
        • 2018-11-08
        相关资源
        最近更新 更多