4

我在Openshift上部署了Web Service。目前我正在開發的是使用我的Gmail帳戶在某個時間發送自動電子郵件。如何使用Gmail API和Java發送電子郵件

所以我一直在記錄自己的兩三天,我已經得出結論,我有兩個選擇:

1)使用JavaMail庫。 2)使用Gmail API。

對於我用什麼第一個選項是以下類:

public class EmailSenderService { 
private final Properties properties = new Properties(); 

private String password = "*******"; 

private Session session; 

private void init() { 

    //ssl 
    properties.put("mail.smtp.host", "smtp.gmail.com"); 
    properties.put("mail.smtp.socketFactory.port", "465"); 
    properties.put("mail.smtp.socketFactory.class", 
      "javax.net.ssl.SSLSocketFactory"); 
    properties.put("mail.smtp.auth", "true"); 
    properties.put("mail.smtp.port", "465"); 

    session = Session.getDefaultInstance(properties, 
     new javax.mail.Authenticator() { 
      protected PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication("eu***@gmail.com",password); 
      } 
     }); 
} 

public void sendEmail(){ 

    init(); 

    //ssl 
    try { 
     Message message = new MimeMessage(session); 
     message.setFrom(new InternetAddress("eu***@gmail.com")); 
     message.setRecipients(Message.RecipientType.TO, 
       InternetAddress.parse("c***[email protected]")); 
     message.setSubject("Testing Subject"); 
     message.setText("Dear Mail Crawler," + 
       "\n\n No spam to my email, please!"); 
     Transport t = session.getTransport("smtp"); 
     t.connect("smtp.gmail.com", "eu***@gmail.com", password); 
     t.sendMessage(message, message.getAllRecipients()); 

     System.out.println("Done"); 

    } catch (MessagingException e) { 
     e.printStackTrace(); 
    } 
} 
} 

並使用此美其名曰:

EmailSenderService ess = new EmailSenderService(); 
     ess.sendEmail(); 

2)我使用的第二個選項是以下:

public class EmailSenderGmailApi { 

/* 
* Atributos 
*/ 
// Check https://developers.google.com/gmail/api/auth/scopes for all available scopes 
private static final String SCOPE = "https://www.googleapis.com/auth/gmail.compose"; 
private static final String APP_NAME = "eu***l"; 
// Email address of the user, or "me" can be used to represent the currently authorized user. 
private static final String USER = "eu***@gmail.com"; 
// Path to the client_secret.json file downloaded from the Developer Console 
private static final String CLIENT_SECRET_PATH = "../app-root/data/eu***.json"; 

private static GoogleClientSecrets clientSecrets; 


/* 
* Metodos 
*/ 

public static Gmail init() throws IOException{ 

    System.out.println("***Working Directory = " + System.getProperty("user.dir")); 


    HttpTransport httpTransport = new NetHttpTransport(); 
    JsonFactory jsonFactory = new JacksonFactory(); 

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

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

    String code = "***"; 

    // 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 
    return 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 
    */ 
    public static MimeMessage createEmail(String to, String from, String subject, 
     String bodyText) throws MessagingException { 

     System.out.println("***Empezando a enviar email..."); 

    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; 
    } 

    /** 
    * 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 
    */ 
    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; 
    } 

    /** 
    * Send an email from the user's mailbox to its recipient. 
    * 
    * @param service Authorized Gmail API instance. 
    * @param userId User's email address. The special value "me" 
    * can be used to indicate the authenticated user. 
    * @param email Email to be sent. 
    * @throws MessagingException 
    * @throws IOException 
    */ 
    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()); 
    } 

}

第一個選項,在調用它的時候,它在Openshift控制檯中顯示的消息如下:

javax.mail.AuthenticationFailedException 
    at javax.mail.Service.connect(Service.java:306) 
    at javax.mail.Service.connect(Service.java:156) 
    at main.java.model.EmailSenderService.sendEmail(EmailSenderService.java:86) 
    at main.java.model.AccessManager.renewPassStepOne(AccessManager.java:234) 
    at main.java.webService.UsuarioService.renewPassStepOne(UsuarioService.java:192) 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
    at java.lang.reflect.Method.invoke(Method.java:606) 
    at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60) 
    at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185) 
    at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75) 
    at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302) 
    ... 

我一直試圖通過自己來解決它,看着谷歌,計算器......但每改變我介紹,我得到同樣的信息。

在選項2中,我不知道如何使用它。我想這樣的事情:

MimeMessage msg = EmailSenderGmailApi.createEmail("ca***@gmail.com", "eu***@gmail.com", "test", "holaaaaa"); 

     EmailSenderGmailApi.sendMessage(
       EmailSenderGmailApi.init(), 
       "cap***@gmail.com", 
       msg); 

反正說實話我已經研究了很多Java郵件的,我希望有人能幫幫我解決任何錯誤我會。

關於Gmail Api,在官方文檔中,我一直無法弄清楚如何發送電子郵件。互聯網上沒有太多的文件。

有人可以借我一隻手嗎?

回答

4

Gmail的API公開的文件有發送電子郵件的指南,它甚至有java的代碼示例:

https://developers.google.com/gmail/api/guides/sending

你上面的代碼似乎並不那麼遙遠,雖然。我首先通過做一些像labels.list()這樣簡單的工作來確保你的Oauth2能夠正常工作,如果這樣做能夠繼續發展到像發送電子郵件那樣更復雜的事情。 (你有正確的想法構建,變成一個字符串,base64url編碼,然後發送它。)你試圖用Gmail API發送它的確切問題是什麼?有一些錯誤輸出或缺少代碼中的東西?

+0

謝謝。我會在這個星期看看它。我會通知你,如果我得到它。我的問題是,我不知道如何創建「Gmail服務」參數在sendMessage中使用它。 – russellhoff 2014-10-20 12:03:09

+0

好的。對於其他Google API(如日曆,驅動器,Plus等)應該是非常標準的,因此他們很可能會開始/快速入門,並顯示它適用於Gmail並具有適當的替代品。我會添加一些標籤,希望能夠幫助您獲得更多的關注。 – 2014-10-20 17:19:23

3

如果你正在使用你的應用程序openshift Java郵件API,

然後在應用程序中添加任何新的圖書館,你必須添加在的pom.xml文件的Maven的配置。換句話說,您必須在pom.xml文件中添加依賴項。

這對於郵件1.4.7 的依賴只是在的pom.xml文件中添加以下代碼

<dependency> 
     <groupId>javax.mail</groupId> 
     <artifactId>mail</artifactId> 
     <version>1.4.7</version> 
    </dependency> 

同樣,任何其他集成,不要忘了添加依賴。 你可以在谷歌搜索: 「maven dependency for ________」

相關問題