Trouble sending emails via Mailgun API

I’m having issues with the Mailgun API. I can connect to the logs endpoint, but when trying to send an email, the request fails. I’ve rewritten my code to test a different setup:

let session = URLSession.shared
var request = URLRequest(url: URL(string: "https://api.mailgun.net/v3/mybox123.mailgun.org/messages")!)
request.httpMethod = "POST"

let messageBody = "from=Test User<[email protected]>&[email protected]&subject=Test&text=Just testing Mailgun API"
let apiKey = "api:key-123456"

request.httpBody = messageBody.data(using: .utf8)
request.setValue("Basic \(encodeBase64(apiKey))", forHTTPHeaderField: "Authorization")

let task = session.dataTask(with: request) { data, response, error in
    if let httpResponse = response as? HTTPURLResponse {
        print("Status code: \(httpResponse.statusCode)")
    }
    // Handle additional response data and errors
}
task.resume()

This variation still returns a 400 or 401 error. I’ve experimented with the message formatting and encoding but haven’t found a solution. What might be causing the issue and how can it be fixed?

hey jack, i had similar issues. check your domain verification on the mailgun dashboard and ensure you’re using the proper private api key. verify the endpoint url for typos. if problems persist, contact mailgun support.

I have encountered a similar issue before with Mailgun. In my experience, the problem might be caused by either an incorrect API key or the domain not being properly verified in your Mailgun account. You might also want to include the Content-Type header set as application/x-www-form-urlencoded and ensure that all parameters in your message body are properly URL encoded. An alternative solution is to try the official Mailgun Swift SDK, which takes care of many low-level details. Checking the detailed logs on your Mailgun dashboard can also provide a clearer error message.

I’ve wrestled with Mailgun API issues before, and there are a few things you might want to double-check. First, ensure your API key is correct and you’re using the private key, not the public one. Also, verify that your domain is properly set up in Mailgun.

One thing that caught me off guard was the Content-Type header. Try adding this line before your request:

request.setValue(“application/x-www-form-urlencoded”, forHTTPHeaderField: “Content-Type”)

Also, URL encode your message body parameters. Swift’s built-in percentEncoded(withAllowedCharacters:) method can help with this.

If you’re still stuck, Mailgun’s logs can be a goldmine of information. They often provide more detailed error messages that can point you in the right direction.

Lastly, don’t hesitate to reach out to Mailgun support. They’re usually quite helpful and can often spot issues that might not be immediately obvious to us developers.