Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get bounce emails from SparkPost without using webhooks?

We are working at the integration of our email application with SparkPost. The only issue we have is getting bounce emails from SparkPost to exclude them from future mailings. Our application retrieves bounce emails directly from the mail server. When the user uses the SparkPost SMTP settings in our software, he cannot retrieve and process bounce emails because SparkPost does not forward bounce messages to the user's bounce email address.

Webhooks will not work for us because they pull data in real time only. If our software is turned to off when the bounce email comes, the bounce will not be caught and will be lost for our software as there is no way to retrieve it at a later time.

So, please, let me know if there is a way to get bounce emails from SparkPost through API or via email just like Amazon SES does. Amazon SES simply forwards bounce emails to the email address specified by the user in our application (Return email header field in the message header).

like image 678
Alex Avatar asked Jan 07 '23 15:01

Alex


2 Answers

If you cannot accept pushed data via HTTP like event webhooks or even our relay webhooks, the next best thing would be our Message Events API(https://www.sparkpost.com/api#/reference/message-events/message-events/search-for-message-events)

You could make a request to just get bounces for last hour like this:

https://api.sparkpost.com/api/v1/message-events?events=bounce,out_of_band

If you want more specific time ranges just add a from/to as well as a timezone if you need that:

https://api.sparkpost.com/api/v1/message-events?from=2015-09-10T00:00&to=2015-09-10T23:59&timezone=America/New_York

like image 99
Bob Evans Avatar answered Jan 10 '23 03:01

Bob Evans


I wrote the following ruby code to get them as CSV:

require 'net/http'
require 'json'
require 'csv'

uri = URI('https://api.sparkpost.com/api/v1/message-events?events=bounce,out_of_band')
req = Net::HTTP::Get.new(uri)
req['Content-Type'] = 'application/json'
req['Authorization'] = ENV['API_KEY'] || raise('please provide API_KEY env variable')

res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |https|
  https.request(req)
end

bounces = JSON.parse(res.body)['results']
puts "#{bounces.count} bounces found"

CSV.open("bounces.csv", "wb") do |csv|
  csv << %w(Timestamp Recipient Reason)
  bounces.each do |bounce|
    csv << [bounce['timestamp'], bounce['rcpt_to'], bounce['reason']]
  end
end

Available as gist here: https://gist.github.com/schmijos/05d2f989c7a5854fe2cd31c666f61c39

like image 22
schmijos Avatar answered Jan 10 '23 04:01

schmijos