java - 使用 Gmail API 发送电子邮件时出错?

标签 java sendmail gmail-api

我正在尝试使用 Gmail java API 发送邮件。我收到以下错误。

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Insufficient Permission"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:145)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:111)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:38)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:314)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1060)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:412)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:345)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:463)
    at GMailLibrary.SendEmail.sendMessage(SendEmail.java:32)
    at GMailLibrary.GMailAuthentication.main(GMailAuthentication.java:85)
Java Result: 1

我已经使用身份验证代码完成了身份验证部分。以下是我发送电子邮件的一段代码。

public class SendEmail 
{
      public static void sendMessage(Gmail service, String userId, MimeMessage email)throws MessagingException, IOException 
      {
            Message message = createMessageWithEmail(email);
            message = service.users().messages().send(userId, message).execute();

            System.out.println("Message id: " + message.getId());
            System.out.println(message.toPrettyString());
      }

      public static Message createMessageWithEmail(MimeMessage email)throws MessagingException, IOException 
      {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            email.writeTo(bytes);
            String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
            Message message = new Message();
            message.setRaw(encodedEmail);

            return message;
      }

      public static MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException 
      {
            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            MimeMessage email = new MimeMessage(session);
            //InternetAddress tAddress = new InternetAddress(to);
            //InternetAddress fAddress = new InternetAddress(from);

            email.setFrom(new InternetAddress(from));
            email.addRecipient(javax.mail.Message.RecipientType.TO,new InternetAddress(to));
            email.setSubject(subject);
            email.setText(bodyText);

            return email;
      }

      public static MimeMessage createEmailWithAttachment(String to, String from, String subject,String bodyText, String fileDir, String filename) throws MessagingException, IOException 
      {
            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);

            MimeMessage email = new MimeMessage(session);
            InternetAddress tAddress = new InternetAddress(to);
            InternetAddress fAddress = new InternetAddress(from);

            email.setFrom(fAddress);
            email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
            email.setSubject(subject);

            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            mimeBodyPart.setContent(bodyText, "text/plain");
            mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");

            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeBodyPart);

            mimeBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(fileDir + filename);

            mimeBodyPart.setDataHandler(new DataHandler(source));
            mimeBodyPart.setFileName(filename);
            String contentType = Files.probeContentType(FileSystems.getDefault()
                .getPath(fileDir, filename));
            mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\"");
            mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64");

            multipart.addBodyPart(mimeBodyPart);

            email.setContent(multipart);

            return email;
      }
}

我通过传递所需信息从主类调用 SendMail 方法。

MimeMessage email = SendEmail.createEmail(to, from, subject, bodytext); 
SendEmail.sendMessage(service, USER, email);

请帮帮我。我已经尽力了。如果需要更多信息,请告诉我。

最佳答案

我在列出消息时遇到了同样的问题。我试图删除 ~/.credentials/gmail-api-quickstar 中的“StoredCredential”,但这无济于事。 您需要的是将“GmailScopes”设置为 MAIL_GOOGLE_COM 对应于完整权限访问。

 /** Global instance of the scopes required by this quickstart. */
private static final List<String> SCOPES =
        Arrays.asList(GmailScopes.MAIL_GOOGLE_COM);

关于java - 使用 Gmail API 发送电子邮件时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25073342/

相关文章:

cron - SAP Hybris 电子商务 : Send Email in CronJob

smtp - 我的服务器和 php mail() 函数将电子邮件发送到垃圾邮件文件夹

google-apps-script - 当 Google 任务标记为 "completed"时如何触发 Google Script

python - Google GMail API `installed` 应用程序显示来自模块 SSL.py 的 IOError 13 w/o sudo

java - 选项卡未调用 onCreateView

java - if-else 和 if return 有什么区别,哪个更好?

java - 在Java中,如何访问新监听器 block 内的静态方法参数?

java - 有没有办法在 Kotlin 协程范围内启动可运行程序?

linux - Bash 邮件 - 仅作为另一个用户发送

google-apps-script - 如何使用谷歌应用程序脚本发送电子邮件草稿