【问题标题】:SendGrid Sending Multiple CopiesSendGrid 发送多个副本
【发布时间】:2015-03-15 06:03:44
【问题描述】:

我正在使用 SendGrid 从我基于 python 的 Heroku 应用程序发送电子邮件。我可以接受它需要 10 分钟左右才能到达我的收件箱,但我收到了三份邮件副本,我可以'不知道为什么。以下是相关代码:

import sendgrid
from sendgrid import SendGridError, SendGridClientError, SendGridServerError
sg = sendgrid.SendGridClient('xxx@heroku.com', 'xxx')
message = sendgrid.Mail()
message.add_to('John Doe <xxx@xxx.com>')
message.set_subject('Example')
message.set_html('Body')
message.set_text('Body')
message.set_from('Dark Knight <xxx@xxx.com>')
message.add_attachment('image.jpg', './image.jpg')
status, msg = sg.send(message)
@app.route('/test2')
def test2():
    sg.send(message)
    return "sent"

当我转到相关路线时,我会收到“已发送”并发送电子邮件,但它再次发送了三份。我不确定为什么。任何帮助都会很棒。

【问题讨论】:

  • 当我从 bash 运行时遇到同样的问题。
  • 你有两次sg.send(message),你在bash里跑什么?
  • 脚本,由于 heroku 页面的加载方式,我不确定它是否被多次调用。

标签: python heroku sendgrid


【解决方案1】:

您在代码中调用了 3 次 sg.send(message)

这里调用了两次:status, msg = sg.send(message) - 这将为status 发送一封邮件并记录它对该变量的响应。然后它将再次发送msg 并记录它对该变量的响应。

然后,当用户点击/test2 时,再次调用该函数,使其总共发出三条消息。

您可以通过以下方式将其更改为记录响应,但只发送一条消息:

import sendgrid
from sendgrid import SendGridError, SendGridClientError, SendGridServerError
sg = sendgrid.SendGridClient('xxx@heroku.com', 'xxx')

def sendMessage(options):
    message = sendgrid.Mail()
    message.add_to('John Doe <xxx@xxx.com>')
    message.set_subject('Example')
    message.set_html('Body')
    message.set_text('Body')
    message.set_from('Dark Knight <xxx@xxx.com>')
    message.add_attachment('image.jpg', './image.jpg')

    // send the message and log the results to status
    msg = sg.send(message)
    return msg

@app.route('/test2')

def test2():
    // send the message, pass any options like email address (not required)
    status = sendMessage(options)
    return status

我在上面添加了一个新函数来发送消息,并为其提供了一个可选的options var,因此您可以使用它来将内容传递给消息,例如不同的电子邮件地址或主题。

【讨论】:

    【解决方案2】:

    我建议您使用 sendgrid sendmail api 发送电子邮件。它高效、快速地发送电子邮件。

    【讨论】:

      【解决方案3】:

      电子邮件一和二: status, msg = sg.send(message) 将发送两封电子邮件,然后将 statusmsg 设置为响应对象。

      邮件三:加载路由后sg.send(message)发送下一封邮件。

      【讨论】:

        猜你喜欢
        • 2022-08-16
        • 2019-04-03
        • 1970-01-01
        • 2015-06-09
        • 1970-01-01
        • 2018-11-09
        • 2012-01-12
        • 1970-01-01
        • 2016-02-08
        相关资源
        最近更新 更多