带有 Gmail 和 OAuth2 的 MailCore2 仅在完全访问范围内发送,即 https://mail.google.com

Posted

技术标签:

【中文标题】带有 Gmail 和 OAuth2 的 MailCore2 仅在完全访问范围内发送,即 https://mail.google.com【英文标题】:MailCore2 with Gmail and OAuth2 sends ONLY with full access scope i.e. https://mail.google.com 【发布时间】:2019-11-18 06:37:20 【问题描述】:

我的应用使用 Mailcore2 通过 Gmail 发送电子邮件。我也为此使用 OAuth2 身份验证。如果选择 FULL 访问范围,则效果很好:https://mail.google.com

但是,Google 建议使用其他范围(发送)。我正在尝试https://www.googleapis.com/auth/gmail.send 和/或https://www.googleapis.com/auth/gmail.compose

Mailcore2 不发送这些范围返回:

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

MailCore2 是否需要完全访问范围? 有什么解决方法吗?

这是我使用 MailCore2 代码发送的,仅适用于 FULL 范围:

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.");
    
];

【问题讨论】:

【参考方案1】:

好吧,回答我自己的问题,因为无法实施解决方法,即 MailCore 需要完全访问 GMail 帐户,Google 不允许这样做。

我最终切换到 HTTP POST/GET 请求,而不是使用 Mailcore。 这是我的其他答案的链接,其中显示了如何发送和接收电子邮件send/receive email with http post in ObjC

【讨论】:

正是我需要听到的,谢谢。所以,我们不能用mailcore来做。我们将在我们的应用程序中为 Gmail 实现 REST API,它只需要对 Gmail 的读取权限【参考方案2】:

Gmail 范围 https://www.googleapis.com/auth/gmail.send 非常适合使用 Gmail API 从您自己的电子邮件地址发送电子邮件。但是,如果您打算通过别名发送电子邮件,则需要为您的项目添加一个受限范围。

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

gmail.settings.basic 范围允许您从连接到经过身份验证的用户的 Gmail 帐户的别名发送电子邮件。

【讨论】:

我尝试了所有范围,包括您建议的范围 - 得到相同的错误,只有完全访问范围有效。我正在使用 Mailcore2 发送/接收。

以上是关于带有 Gmail 和 OAuth2 的 MailCore2 仅在完全访问范围内发送,即 https://mail.google.com的主要内容,如果未能解决你的问题,请参考以下文章

访问未授予或过期 GMAIL API 和 Oauth2 / 如何使用 GMAIL API 和 GSuite 域设置电子邮件签名

oAuth2 gmail 集成错误

如何使用 OAuth2.0 生成 XOAUTH 参数以与 Gmail IMAP 协议一起使用?

如何使用 Twisted 通过 OAuth2.0 身份验证检查 Gmail

python & smtplib:是不是可以使用 oauth2 通过 gmail 发送邮件?

python & smtplib:是不是可以使用 oauth2 通过 gmail 发送邮件?