I don't think it's possible to add a rule to your firewall that dynamically checks whether the connection is going to a domain that resolves to this IP.
However, as you already tried, adding every IP they have to the firewall is a solution. To get all possible IPs I'd do:
// Find the authoritative nameserver
// Your local nameserver potentially only returns the cached, first record
$ dig api.mailgun.net IN SOA
;; AUTHORITY SECTION:
mailgun.net. 899 IN SOA ns-1447.awsdns-52.org. awsdns-hostmaster.amazon.com. 1 7200 900 1209600 86400
// Query that for all the records
$ dig +short api.mailgun.net IN A @ns-1447.awsdns-52.org.
34.200.7.26
52.200.96.214
52.73.0.101
52.21.40.223
52.86.239.198
34.232.33.59
Or you just need to add a rule that allows all incoming TCP response traffic for connections you make. Assuming all outgoing traffic is allowed anyways.
To do this, add an incoming ACCEPT rule covering the Ephemeral Port Range:
- Source/Dest IP: any
- Source port: any
- Dest port: 32768-65535
- Protocol: TCP
- TCP flags: ack