MailCore2 with Gmail and OAuth2 sends ONLY with full access scope i.e. https://mail.google.com

571 Views Asked by At

My app sends emails via Gmail using Mailcore2. I use OAuth2 authentication for that too. It works great if FULL access scope selected: https://mail.google.com

However, Google proposed to use other scopes (send). I am trying out https://www.googleapis.com/auth/gmail.send and/or https://www.googleapis.com/auth/gmail.compose

Mailcore2 does not send with these scopes returning:

MCOSMTPResponseCodeKey=535, NSLocalizedDescription=Unable to authenticate with the current session's credentials., MCOSMTPResponseKey=5.7.8 Username and Password not accepted.

Does MailCore2 need full access scope? Any workarounds?

here is my sending with MailCore2 code that works only with FULL scope:

MCOSMTPSession *smtpSession = [[MCOSMTPSession alloc] init];
smtpSession.hostname = @"smtp.gmail.com";
smtpSession.port = 465;

[smtpSession setAuthType:MCOAuthTypeXOAuth2];
[smtpSession setOAuth2Token:delAuthAccessToken];//from oauth2
[smtpSession setUsername:delAuthUserEmail];

smtpSession.authType =MCOAuthTypeXOAuth2;
smtpSession.connectionType=MCOConnectionTypeTLS;

MCOMessageBuilder *builder = [[MCOMessageBuilder alloc] init];
NSMutableArray *to = [[NSMutableArray alloc] init];
[to addObject:[MCOAddress addressWithDisplayName:delSendName mailbox:delSendEmail]];
MCOAddress *from = [MCOAddress addressWithDisplayName:delAuthUserEmail mailbox:delAuthUserEmail];

[[builder header] setFrom:from];
[[builder header] setTo:to];
[[builder header] setSubject:@"Sent By MyApp"];
[builder setTextBody:delMessage];
NSData * rfc822Data = [builder data];

MCOSMTPSendOperation *sendOperation =[smtpSession sendOperationWithData:rfc822Data];

[sendOperation start:^(NSError *error) {
    if(error) {
        NSLog(@"Error sending email: %@", error);

    } else {
        NSLog(@"Message sent sucessfully.");
    }
}];
2

There are 2 best solutions below

1
Amit Agarwal On

The Gmail scope https://www.googleapis.com/auth/gmail.send is perfect for sending emails with the Gmail API from your own email address. However, if you are planning to send email from an alias, you'd need to add a restricted scope to your project.

https://www.googleapis.com/auth/gmail.settings.basic

The gmail.settings.basic scope lets you send emails from aliases connected to the Gmail account of the authenticated user.

1
Boris Gafurov On

Well, answering my own question cause no workarounds can be implemented i.e. MailCore requires full access to GMail account, Google won't allow that.

I ended up switching to HTTP POST/GET requests instead of using Mailcore. Here is a link to my other answer that shows an example how to send and receive emails send/receive email with http post in ObjC