AWS iOS SDK: Sending Email via AWSSES - ios

Does anyone have any experience using the latest Amazon AWS SDK 2.3.6 for sending an email via SES SMTP? I currently have an api key, secret, and smtp_url.
Thanks!

Just figured it out. I confess Amazon's documentation is a little dense. Hope this helps someone else!
AWSSESSendEmailRequest *awsSESSendEmailRequest = [AWSSESSendEmailRequest new];
awsSESSendEmailRequest.source = #"source#email";
AWSSESDestination *awsSESDestination = [AWSSESDestination new];
awsSESDestination.toAddresses = [NSMutableArray arrayWithObjects:#"to#email",nil];
awsSESSendEmailRequest.destination = awsSESDestination;
AWSSESMessage *awsSESMessage = [AWSSESMessage new];
AWSSESContent *awsSESSubject = [AWSSESContent new];
awsSESSubject.data = #"Subject goes here";
awsSESSubject.charset = #"UTF-8";
awsSESMessage.subject = awsSESSubject;
AWSSESContent *awsSESContent = [AWSSESContent new];
awsSESContent.data = #"Message goes here";
awsSESContent.charset = #"UTF-8";
AWSSESBody *awsSESBody = [AWSSESBody new];
awsSESBody.text = awsSESContent;
awsSESMessage.body = awsSESBody;
awsSESSendEmailRequest.message = awsSESMessage;
AWSStaticCredentialsProvider *credentialsProvider = [[AWSStaticCredentialsProvider alloc] initWithAccessKey:#"ACCESS-KEY"
secretKey:#"SECRET-KEY"];
AWSServiceConfiguration *configuration = [[AWSServiceConfiguration alloc] initWithRegion:AWSRegionUSWest2
credentialsProvider:credentialsProvider];
[AWSServiceManager defaultServiceManager].defaultServiceConfiguration = configuration;
[[AWSSES defaultSES] sendEmail:awsSESSendEmailRequest completionHandler:^(AWSSESSendEmailResponse * _Nullable response, NSError * _Nullable error) {
if (error)
{
// error
}
else
{
// success
}
}];

The code snippet of Send email in Swift 3.0 below.
let serviceRegionType = AWSRegionType.usEast1
let credentialsProvider = AWSStaticCredentialsProvider.init(accessKey: "access", secretKey: "secret")
let configuration = AWSServiceConfiguration(region: serviceRegionType, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = configuration
let subject = AWSSESContent()
subject?.data = "Subject"
subject?.charset = "UTF-8"
let messageBody = AWSSESContent()
messageBody?.data = "Sample Message body"
messageBody?.charset = "UTF-8"
let body = AWSSESBody()
body?.text = messageBody
let theMessage = AWSSESMessage()
theMessage?.subject = subject
theMessage?.body = body
let destination = AWSSESDestination()
destination?.toAddresses = ["toaddress"]
let send = AWSSESSendEmailRequest()
send?.source = "source mail"
send?.destination = destination
send?.message = theMessage
AWSSES.default().sendEmail(send!) { (response:AWSSESSendEmailResponse?, mailError: Error?) in
print(mailError?.localizedDescription)
if ((response?.messageId) != nil) {
print("Mail has delivered succesfully")
} else {
print("Mail has failed to delivered")
}
}

To add to unicornherder's answer: your code worked well for my iOS app. However, because my app users are authenticated by Cognito, I did not need your code used to set up AWSStaticCredentialsProvider. This already happens in my AppDelegate per the sample code.
I did need to give my Cognito-authorized users permission to use SES, however. This last step is accomplished by adding the permission to the authUser role.

Related

mailcore2 via SMTP Outlook.com gives Error Domain=MCOErrorDomain Code=1 "A stable connection to the server could not be established."

I am setting up outlook.com with mailcore2 on iOS9 in Objective-C. I have gmail working already with both imap and smtp. I can fetch emails fine from outlook.com but when I try and send an email I get the following error:
Error Domain=MCOErrorDomain Code=1 "A stable connection to the server
could not be established."
Below is a sample of my code:
MCOSMTPSession *session = [[MCOSMTPSession alloc] init];
[session setAuthType:MCOAuthTypeXOAuth2Outlook];
[session setOAuth2Token:accessToken];
[session setUsername:#"user#outlook.com"];
[session setHostname:#"smtp-mail.outlook.com"];
[session setPort:25]; //also tried 587
[session setConnectionType:MCOConnectionTypeStartTLS]; //Also tried MCOConnectionTypeTLS and MCOConnectionTypeClear
[session setCheckCertificateEnabled:false];
MCOSMTPSendOperation *sendOperation = [session sendOperationWithData:data];
[sendOperation start:^(NSError *error) {
}];
I also tried the checkAccountOperationWithFrom operation but that also gave the same error.
I am not able to fetch emails from Outlook, can you tell me what are the changes to be done in my Imap Settings.Below is the code i am using..
session = [[MCOIMAPSession alloc]init];
session.hostname = #"imap-mail.outlook.com";
session.username = #"dummy#outlook.com";
session.password = nil;
session.port = 993;
session.OAuth2Token = accessToken;
session.connectionType = MCOConnectionTypeStartTLS;
session.authType = MCOAuthTypeSASLLogin;
session.checkCertificateEnabled = false;
Swift 5, iOS 13, Xcode Version 11.3.1 (11C504)
Also Need to Disable Captcha : [https://accounts.google.com/DisplayUnlockCaptcha][1]
Response: Successfully sent email!
Here is the perfect solution:
#IBAction func btnSendMailClicked(_ sender: UIButton) {
print(#function)
let smtpSession = MCOSMTPSession()
smtpSession.hostname = "smtp.gmail.com"
smtpSession.username = "emailaddress#gmail.com"
smtpSession.password = "password" //You can create [App Password from gmail setting][1]
smtpSession.port = 587 //25
smtpSession.authType = MCOAuthType.saslPlain
smtpSession.connectionType = MCOConnectionType.startTLS
smtpSession.isCheckCertificateEnabled = false
smtpSession.connectionLogger = {(connectionID, type, data) in
if data != nil {
if let string = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
NSLog("Connectionlogger: \(string)")
}
}
}
let builder = MCOMessageBuilder()
builder.header.to = [MCOAddress(displayName: "Swifty Developers", mailbox: "swiftydevelopers#gmail.com")!]
builder.header.from = MCOAddress(displayName: "Mehul Parmar", mailbox: "mehulasjack#gmail.com")
builder.header.subject = "My message"
builder.htmlBody = "Yo Rool, this is a test message!"
let rfc822Data = builder.data()
let sendOperation = smtpSession.sendOperation(with: rfc822Data)
sendOperation?.start { (error) -> Void in
if (error != nil) {
NSLog("Error sending email: \(String(describing: error))")
} else {
NSLog("Successfully sent email!")
}
}
}

Verify P12 Certificate for VPN Conection

I want to connect Vpn via Code Using Network Extension framework .
I have a P12 Certificate to make VPN Connection also a Root CA (Crt) Certificate to Verify the P12 Certificate .
My problem is to verify The P12 certificate programatically .
I am Using below code to connect to VPN .
let p = NEVPNProtocolIKEv2()
p.authenticationMethod = NEVPNIKEAuthenticationMethod.None
p.useExtendedAuthentication = true
p.serverAddress = "102.xxx.xxx.xx"
p.remoteIdentifier = "102.xxx.xxx.xx"
p.disconnectOnSleep = false
p.deadPeerDetectionRate = NEVPNIKEv2DeadPeerDetectionRate.Medium
// TODO: Add an option into config page
manager.localizedDescription = "VPN On - \(title)"
if let grp = group {
p.localIdentifier = grp
} else {
p.localIdentifier = "VPN"
}
if let username = account {
p.username = username
}
if let certficiateData = certificate {
p.authenticationMethod = NEVPNIKEAuthenticationMethod.Certificate
p.serverCertificateCommonName = server
p.serverCertificateIssuerCommonName = "Root-CA"
if #available(iOSApplicationExtension 8.3, *) {
p.certificateType = NEVPNIKEv2CertificateType.RSA
} else {
// Fallback on earlier versions
}
// Here i Provide Certificate Data .
let rootCertPath = NSBundle.mainBundle().pathForResource("certificate", ofType: "p12")
let certficiateData = NSData(contentsOfFile: rootCertPath!)
// I need to verify above P12 Certificate with rootCA.crt before Passing to identityData
p.identityData = certficiateData
}
manager.enabled = true
manager.`protocol` = p

Null Error with eWAY iOS SDK

I am currently writing an iOS application utilising a credit card SDK from a company called eWAY.
I am attempting to get it working in a sandbox test environment but I keep receiving a null error.
NSLog output (The "EWAY ERROR" is part of my NSLog message)
2015-10-15 12:25:40.127 EwayTest[1351:37919] EWAY ERROR: <null> ()
Im literally using the example on the webpage: https://www.eway.com.au/developers/sdk/ios
Gateway:
I am using the URL: https://api.sandbox.ewaypayments.com/ gateway as specified.
My code:
- (IBAction)btnPress:(id)sender
{
Transaction *transaction = [[Transaction alloc] init];
Customer *customerObj = [[Customer alloc] init];
customerObj.Reference = #"A12345";
customerObj.Title = #"Mr.";
customerObj.FirstName = #"Nico";
customerObj.LastName = #"Vulture";
customerObj.CompanyName = #"All Web Pty Ltd";
customerObj.JobDescription = #"Developer";
customerObj.Phone = #"09 889 0986";
customerObj.Mobile = #"09 889 0986";
Address *customerAddress = [[Address alloc] init];
customerAddress.Street1 = #"Level 5";
customerAddress.Street2 = #"369 Queen Street";
customerAddress.City = #"Sydney";
customerAddress.State = #"NSW";
customerAddress.PostalCode = #"2010";
customerAddress.Country = #"au";
customerObj.Address = customerAddress;
CardDetails *cardDetails = [[CardDetails alloc] init];
cardDetails.Name = #"Nico Vulture";
cardDetails.Number = #"378282246310005";
cardDetails.ExpiryMonth = #"10";
cardDetails.ExpiryYear = #"19";
cardDetails.CVN = #"836";
customerObj.CardDetails = cardDetails;
transaction.Customer = customerObj;
//payment
Payment *payment = [[Payment alloc] init];
payment.Payment = 100;
payment.InvoiceNumber = #"Inv 21540";
payment.InvoiceDescription = #"Individual Invoice Description";
payment.InvoiceReference = #"513456";
payment.CurrencyCode = #"AUD";
transaction.Payment = payment;
//Make payment
[RapidAPI submitPayment:transaction completed:^(SubmitPaymentResponse *submitPaymentResponse) {
if(submitPaymentResponse.Status == Accepted)
{
NSLog(#"EWAY: Accepted");
}
else if (submitPaymentResponse.Status == Success)
{
// The API Call completed successfully.
NSLog(#"EWAY: Success");
}
else if(submitPaymentResponse.Status == Error)
{
// An error occurred with the API Call.
[RapidAPI userMessage:submitPaymentResponse.Errors Language:#"EN" completed:^(UserMessageResponse *userMessageResponse) {
NSString *msg = [NSString stringWithFormat:#"%# \n %#",userMessageResponse.Errors, userMessageResponse.Messages];
NSLog(#"EWAY ERROR: %#",msg);
}];
}
}];
}
I have however noticed when I change up the gateway (URL) https://api.ewaypayments.com/DirectPayment.json I get an error output of:
EWAY ERROR: S9990
(null)
Which as on the website indicates a "Library does not have Endpoint initialised, or not initialise to a URL" error.
I have been in contact with the company, it must be me doing something wrong here. Has anyone had any experience with this and could provide some insight as to what I'm missing?
Just to update anyone who is or was experiencing this problem. The code works perfectly there was a bug in the SDK that has since been fixed.

Authorize.net TransactionResponse error in iOS

I have created the testing transaction request using purchaseWithRequest, always i am getting error
Transactions of this market type cannot be processed on this system
My Code:
- (void) createTransaction {
AuthNet *an = [AuthNet getInstance];
[an setDelegate:self];
CreditCardType *creditCardType = [CreditCardType creditCardType];
creditCardType.cardNumber = #"4007000000027";
creditCardType.cardCode = #"100";
creditCardType.expirationDate = #"0215";
PaymentType *paymentType = [PaymentType paymentType];
paymentType.creditCard = creditCardType;
ExtendedAmountType *extendedAmountTypeTax = [ExtendedAmountType extendedAmountType];
extendedAmountTypeTax.amount = #"0";
extendedAmountTypeTax.name = #"Tax";
ExtendedAmountType *extendedAmountTypeShipping = [ExtendedAmountType extendedAmountType];
extendedAmountTypeShipping.amount = #"0";
extendedAmountTypeShipping.name = #"Shipping";
LineItemType *lineItem = [LineItemType lineItem];
lineItem.itemName = #"Soda";
lineItem.itemDescription = #"Soda";
lineItem.itemQuantity = #"1";
lineItem.itemPrice = #"1.00";
lineItem.itemID = #"1";
TransactionRequestType *requestType = [TransactionRequestType transactionRequest];
requestType.lineItems = [NSMutableArray arrayWithObject:lineItem];
requestType.amount = #"1.00";
requestType.payment = paymentType;
requestType.tax = extendedAmountTypeTax;
requestType.shipping = extendedAmountTypeShipping;
CreateTransactionRequest *request = [CreateTransactionRequest createTransactionRequest];
request.transactionRequest = requestType;
request.transactionType = AUTH_ONLY;
request.anetApiRequest.merchantAuthentication.mobileDeviceId =
[[Utility getDeviceID]
stringByReplacingOccurrencesOfString:#"-" withString:#"_"];
request.anetApiRequest.merchantAuthentication.sessionToken = sessionToken;
[an purchaseWithRequest:request];
}
Which give call back to this delegate method,
- (void) requestFailed:(AuthNetResponse *)response {
// Handle a failed request
// getting callback to this method
}
- (void) connectionFailed:(AuthNetResponse *)response {
// Handle a failed connection
}
- (void) paymentSucceeded:(CreateTransactionResponse *) response {
// Handle payment success
}
Note: my mobileDeviceRegistrationSucceeded and mobileDeviceLoginSucceeded, only purchaseWithRequestFailed
TransactionResponse.errors = (
"Error.errorCode = 87\nError.errorText = Transactions of this market type cannot be processed on this system.\n"
)
A Market Type Error (Error 87)
Error Text: (87) Transactions of this market type cannot be processed on this system.
What It Means
This error indicates that the account that you are using was created for Card Present (retail) transactions, but you are trying to integrate to our Card Not Present (e-commerce) APIs or vice versa. The only way to resolve this is to open a new test account with the correct market type. If the error is occurring with a live account, the merchant will need to call Customer Support to see how to get the correct account.
In the coming months, Authorize.Net will be supporting blended accounts that support both Card Present and Card Not Present transactions, which will eliminate this error. When these accounts are available, we’ll post an announcement in the News and Announcements board.

iOS5 - How to parse JSON response from Facebook [duplicate]

I am using Facebook Graph API...for fetching the data of news feed of the facebook profile..
and here is the response that i am getting in the console
{
application = {
id = 2309869772;
name = Links;
};
"created_time" = "2011-02-10T09:44:27+0000";
from = {
id = 1845195019;
name = "Paritosh Raval";
};
icon = "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif";
id = "1845195019_192144087475935";
likes = {
count = 1;
data = (
{
id = 1845195019;
name = "Paritosh Raval";
}
);
};
link = "http://www.facebook.com/AMDAVAD";
name = "once you live in AHMEDABAD u cannot live anywhere else in the world..";
picture = "http://profile.ak.fbcdn.net/hprofile-ak-snc4/203562_115963658443669_4129246_n.jpg";
properties = (
{
name = Page;
text = "21,803 people like this.";
}
);
type = link;
"updated_time" = "2011-02-10T09:44:27+0000";
},
{
application = {
id = 2392950137;
name = Video;
};
"created_time" = "2011-02-02T04:18:22+0000";
description = "must watch and explore :))";
from = {
id = 1845195019;
name = "Paritosh Raval";
};
icon = "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif";
id = "1845195019_194836027209359";
likes = {
count = 1;
data = (
{
id = 100000701228096;
name = "Bhargav Jani";
}
);
};
link = "http://www.facebook.com/video/video.php?v=152586058110610&comments";
name = "It Happens Only in....";
"object_id" = 152586058110610;
picture = "http://vthumb.ak.fbcdn.net/hvthumb-ak-snc4/50893_152586468110569_152586058110610_18299_1832_t.jpg";
properties = (
{
name = Length;
text = "0:54";
}
);
source = "http://video.ak.fbcdn.net/cfs-ak-ash2/70137/56/152586058110610_53804.mp4?oh=481e53b824f6db8e3195fc9c0d07571d&oe=4DAFC300&__gda__=1303364352_7670272db65e93ec75dcaaed16b6d805";
type = video;
"updated_time" = "2011-02-02T04:18:22+0000";
}
And I want to show every data in the organized structure in the console. Can anyone help me with this?
it's unclear what you exactly asking but I try to answer.
First of all you need to parse this response in the method
- (void)request:(FBRequest *)request didLoad:(id)result of Facebook iOS SDK
result can be a string, a NSArray if you have multiple results and NSDictionary
In you console output we can see NSDictionary with included arrays and dictionaries in it.
I have little tutorial about it but it's on russian only and site is down today :( so i just copy one example from my article.
Let say we want to know what facebook user Likes
- (IBAction)getUserInfo:(id)sender {
[_facebook requestWithGraphPath:#"me/likes" andDelegate:self];
}
if we try this Graph API response in browser or output to console we can see what this request returns. It returns dictionary with one and only key - "data" and corresponded array to this key. This array contents dictionary objects again with keys -
«name»,"category","id","created_time". Dont forget request «user_likes» permission before.
So we have parsing method like that:
- (void)request:(FBRequest *)request didLoad:(id)result {
if ([result isKindOfClass:[NSArray class]]) {
result = [result objectAtIndex:0];
}
if ([result objectForKey:#"owner"]) {
[self.label setText:#"Photo upload Success"];
} else if ([result objectForKey:#"data"]){
NSArray *likes = [result objectForKey:#"data"];
NSString *text=#"You don't like Steve";
for (NSDictionary* mylike in likes) {
NSString *mylikeName = [mylike objectForKey:#"name"];
if ([mylikeName isEqualToString:#"Steve Jobs"]) {
text=#"You like Steve";
break;
}
}
[self.label setText:text];
}
};
You can parse you result same way and fill your object's variables and then use it to display information in TableView for example. good luck!

Resources