如何通过标签筛选Mailgun日志/消息?Ruby调用Mailgun API实现方法
Hey there! Let's break down how to filter your Mailgun logs and messages by tags—both generally and specifically in your Ruby setup with RestClient.
1. General Tag Filtering Methods
Using the Mailgun Dashboard
- Navigate to your Mailgun dashboard and open the Logs section.
- Filter by tag directly in the search bar: type
tag:your-tag-value(e.g.,tag:sample-tag-here) and hit enter to see all associated messages. - Alternatively, use the dropdown filter menu, select "Tag", and pick from your existing tag list.
Using the Mailgun API
You can filter via the API in two supported ways:
- Request Header: Include the
X-Mailgun-Tagheader with your target tag value. - Query Parameter: Append
?tag=your-tag-valueto the API endpoint URL.
Key endpoints to use:
- For logs:
/v3/{domain}/events - For stored messages (if you have message storage enabled):
/v3/{domain}/messages
2. Ruby Implementation with RestClient
You already started setting up the X-Mailgun-Tag header—great! Let's flesh out full working examples for both logs and stored messages, plus show the query parameter approach as an alternative.
Fetch Filtered Logs (Using Header)
require 'rest-client' require 'json' api_key = ENV["MAILGUN_API_KEY"] domain = ENV["MAILGUN_DOMAIN"] target_tag = 'sample-tag-here' headers = { "X-Mailgun-Tag" => target_tag, "Accept" => "application/json" } response = RestClient.get( "https://api:#{api_key}@api.mailgun.net/v3/#{domain}/events", headers ) # Parse and use the filtered logs filtered_logs = JSON.parse(response.body) puts filtered_logs["items"] # Contains your tag-matching log entries
Fetch Filtered Logs (Using Query Parameter)
If you prefer query params over headers, here's how to structure the request:
require 'rest-client' require 'json' api_key = ENV["MAILGUN_API_KEY"] domain = ENV["MAILGUN_DOMAIN"] target_tag = 'sample-tag-here' response = RestClient.get( "https://api:#{api_key}@api.mailgun.net/v3/#{domain}/events?tag=#{target_tag}", { accept: :json } ) filtered_logs = JSON.parse(response.body) puts filtered_logs["items"]
Fetch Stored Messages by Tag
If you have Mailgun's message storage enabled, use the same filtering logic for stored messages:
require 'rest-client' require 'json' api_key = ENV["MAILGUN_API_KEY"] domain = ENV["MAILGUN_DOMAIN"] target_tag = 'sample-tag-here' headers = { "X-Mailgun-Tag" => target_tag, "Accept" => "application/json" } response = RestClient.get( "https://api:#{api_key}@api.mailgun.net/v3/#{domain}/messages", headers ) filtered_messages = JSON.parse(response.body) puts filtered_messages["items"]
Quick Notes
- Tag values are case-sensitive—double-check you're using the exact case from when you sent the messages.
- Ensure your API key has read permissions for logs/messages on your domain.
- Combine tag filters with other parameters (like
event=deliveredfor logs) to narrow results even further.
内容的提问来源于stack exchange,提问作者aldrien.h
相关产品推荐
相关产品推荐

