无法使用Java中的Gmail API发送邮件

时间:2015-11-10 11:32:59

标签: java gmail-api

我正在尝试使用我的Gmail帐户发送邮件。我已完成以下步骤 -

(i)在开发者控制台中创建了一个服务帐户。 (ii)获得私钥文件。 (iii)在我的代码中使用该私钥文件。

代码 -

package com.gmail.test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.repackaged.org.apache.commons.codec.binary.Base64;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.GmailScopes;
import com.google.api.services.gmail.model.Message;



public class GmailOauthTest {

      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();
        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 baos = new ByteArrayOutputStream();
        email.writeTo(baos);
        String encodedEmail = Base64.encodeBase64URLSafeString(baos.toByteArray());
        Message message = new Message();
        message.setRaw(encodedEmail);
        return message;
      }

      public static void main(String[] args) {

        String emailAddress = "#############@developer.gserviceaccount.com";
        JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
        try {
            HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

            File file = new File(p12File);

            Set<String> scopes = new HashSet<String>();
            scopes.add(GmailScopes.GMAIL_SEND);
            scopes.add(GmailScopes.GMAIL_COMPOSE);

            GoogleCredential credential = new GoogleCredential.Builder()
                    .setTransport(httpTransport)
                    .setJsonFactory(JSON_FACTORY)
                    .setServiceAccountId(emailAddress)
                    .setServiceAccountUser(userAccount)
                    .setServiceAccountPrivateKeyFromP12File(file)
                    .setServiceAccountScopes(scopes)
                    .build();
            Gmail gmail = new Gmail
                    .Builder(httpTransport, JSON_FACTORY, credential)
                    .setApplicationName(ApplicationName)
                    .build();

            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("Test Mail");
            message.setText("Test Mail");
            sendMessage(gmail, "me", message);


        } catch (GeneralSecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MessagingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

我收到以下异常 -

Exception in thread "main" java.lang.NullPointerException
    at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)
    at com.google.api.client.util.Preconditions.checkNotNull(Preconditions.java:127)
    at com.google.api.client.json.jackson2.JacksonFactory.createJsonParser(JacksonFactory.java:92)
    at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:85)
    at com.google.api.client.json.JsonObjectParser.parseAndClose(JsonObjectParser.java:81)
    at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:88)
    at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:287)
    at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
    at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
    at com.gmail.test.GmailOauthTest.sendMessage(GmailOauthTest.java:44)
    at com.gmail.test.GmailOauthTest.main(GmailOauthTest.java:101)

我看到了一些其他线程,但无法找到解决方案。任何帮助将不胜感激。

0 个答案:

没有答案