How to Send Emails in Swift Using Mailgun

Swift Send Email with MailGun

In python, the auth is being passed in the header.

You have to do a http post request, passing both the header and the body.

This is a working code:

func test() {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.mailgun.net/v3/sandbox(Personal info).mailgun.org/messages")!)
request.HTTPMethod = "POST"
let data = "from: Excited User <(Personal info)>&to: [bar@example.com,(Personal info)]&subject:Hello&text:Testinggsome Mailgun awesomness!"
request.HTTPBody = data.dataUsingEncoding(NSASCIIStringEncoding)
request.setValue("key-(Personal info)", forHTTPHeaderField: "api")
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in

if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}

})
task.resume()
}

How to send emails in Swift using Mailgun

At this point I've answered my own question. The process isn't too terrible. Install mailgun using cocoapods.
Link the objective-c code that is needed using an objective-c bridging header.
Create an objective c file to house your method that will call the mailgun operation, and use it.

#import <Foundation/Foundation.h>
#import <mailgun/Mailgun.h>

@interface mailTest: NSObject
- (void) sendMail: (NSString*)email;

@end

Then in my swift code I just call:

            var test: mailTest = mailTest()
test.sendMail("testemail@testemail.com")

Here is the mailTest header file. I created a .m file that implements the sendMail method and calls the code from the API and it works great. The only other thing that could be challenging is setting up the mailgun account and configuring your domain so that emails can be sent, but that isn't code related.

Sending Emails With Swift Mailer on Google Cloud using the Mailgun Service Provider

Looks like on Compute Engine you should use port 2525 because outbound connections on ports 25, 465, and 587 is not allowed. You can read more on Mailgun documentation and Google Cloud Platform documentation and more.



Related Topics



Leave a reply



Submit