使用Java使用Gmail API发送电子邮件时出错

时间:2015-03-30 21:12:43

标签: java gmail-api

我正在尝试使用以下代码,以便使用新的Gmail API发送电子邮件。我从不同的网站收集它,特别是从谷歌的例子中收集它。 代码编译成功,在成功授权后,代码仍在运行并运行,没有任何结果!它永远不会停止! 当然,它根本不发送任何电子邮件! 因此,我需要您的意见,帮助和建议来解决此问题。 我很乐意向您发送任何进一步的细节或要求Jar的。 我认为错误可能在主类中,我试图修复它但失败了。 非常感谢您的帮助。 谢谢

package test1;

import com.google.api.client.auth.oauth2.Credential;
import java.util.Arrays;
import java.util.Properties;
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.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleOAuthConstants;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.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.model.Message;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class Test1 {

    public static void main(String[] args) throws IOException, MessagingException ,FileNotFoundException //throws sendMail
    {
      //  System.out.println(getRequestUrl());
      //  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      //  emailCredentialSetup(br.readLine());
      //  sendMail("Alwa@gmail.com", "TEST1eee", "Hello");
      //  System.out.println("test");
      //  httpTransport = GoogleNetHttpTransport.newTrustedTransport();

      // initialize the data store factory
      // dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

      // authorization
        System.out.println(getRequestUrl());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        emailCredentialSetup(br.readLine());
        Test1 sendMail = new Test1();
        MimeMessage mail2;
        mail2 =  sendMail.createEmail("Alwa@gmail.com", "Alwa1@gmail.com", "yyyyyy", "kkkkkkkk");
        System.out.println("Obtener MIME: " + mail2);
        //sendMail(gmailClient, "from@gmail.com", mail2);
        sendMail("Alwa1@gmail.com", "TEST1eee", "Hello");

    }
    private static final String SCOPE = "https://www.googleapis.com/auth/gmail.modify";
    private static final String APP_NAME = "service_account";
    // Path to the client_secret.json file deloper Console
    private static final String CLIENT_SECRET_PATH = "./My Project-52.json";
    private static GoogleClientSecrets clientSecrets;
    private static GoogleAuthorizationCodeFlow flow;
    private static HttpTransport httpTransport;
    private static JsonFactory jsonFactory;
    private static Gmail service;

    public static String getRequestUrl() throws FileNotFoundException, IOException{
        httpTransport = new NetHttpTransport();
        jsonFactory = new JacksonFactory();

        clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(
                CLIENT_SECRET_PATH));

        // Allow user to authorize via url.
        flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
        .setAccessType("online").setApprovalPrompt("auto").build();

        String url = flow.newAuthorizationUrl()
                .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).build();

        return url;
    }

    public static void sendMail(String to, String sub, String body) throws IOException, MessagingException {

        Message message = createMessageWithEmail(createEmail(to, "me", sub, body));
        message = service.users().messages().send("me", message).execute();

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

    static void emailCredentialSetup(String code) throws IOException {
        // Generate Credential using retrieved code.
        GoogleTokenResponse response = flow.newTokenRequest(code)
                .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI)
                .execute();
        GoogleCredential credential = new GoogleCredential()
                .setFromTokenResponse(response);

        // Create a new authorized Gmail API client
        service = new Gmail.Builder(httpTransport, jsonFactory,
                credential).setApplicationName(APP_NAME).build();
    }

    /**
       * Create a MimeMessage using the parameters provided.
       *
       * @param to Email address of the receiver.
       * @param from Email address of the sender, the mailbox account.
       * @param subject Subject of the email.
       * @param bodyText Body text of the email.
       * @return MimeMessage to be used to send email.
       * @throws MessagingException
     * @throws UnsupportedEncodingException 
       */
      private static MimeMessage createEmail(String to, String from, String subject,
          String bodyText) throws MessagingException, UnsupportedEncodingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        MimeMessage email = new MimeMessage(session);

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

      /**
       * Create a Message from an email
       *
       * @param email Email to be set to raw of message
       * @return Message containing base64 encoded email.
       * @throws IOException
       * @throws MessagingException
       */
      private 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;
      }   
}

0 个答案:

没有答案