Advertisement
Guest User

Untitled

a guest
Jul 5th, 2017
604
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.14 KB | None | 0 0
  1. public class EmailSenderService {
  2. private final Properties properties = new Properties();
  3.  
  4. private String password = "*******";
  5.  
  6. private Session session;
  7.  
  8. private void init() {
  9.  
  10. //ssl
  11. properties.put("mail.smtp.host", "smtp.gmail.com");
  12. properties.put("mail.smtp.socketFactory.port", "465");
  13. properties.put("mail.smtp.socketFactory.class",
  14. "javax.net.ssl.SSLSocketFactory");
  15. properties.put("mail.smtp.auth", "true");
  16. properties.put("mail.smtp.port", "465");
  17.  
  18. session = Session.getDefaultInstance(properties,
  19. new javax.mail.Authenticator() {
  20. protected PasswordAuthentication getPasswordAuthentication() {
  21. return new PasswordAuthentication("eu***@gmail.com",password);
  22. }
  23. });
  24. }
  25.  
  26. public void sendEmail(){
  27.  
  28. init();
  29.  
  30. //ssl
  31. try {
  32. Message message = new MimeMessage(session);
  33. message.setFrom(new InternetAddress("eu***@gmail.com"));
  34. message.setRecipients(Message.RecipientType.TO,
  35. InternetAddress.parse("c***6@gmail.com"));
  36. message.setSubject("Testing Subject");
  37. message.setText("Dear Mail Crawler," +
  38. "nn No spam to my email, please!");
  39. Transport t = session.getTransport("smtp");
  40. t.connect("smtp.gmail.com", "eu***@gmail.com", password);
  41. t.sendMessage(message, message.getAllRecipients());
  42.  
  43. System.out.println("Done");
  44.  
  45. } catch (MessagingException e) {
  46. e.printStackTrace();
  47. }
  48. }
  49. }
  50.  
  51. EmailSenderService ess = new EmailSenderService();
  52. ess.sendEmail();
  53.  
  54. public class EmailSenderGmailApi {
  55.  
  56. /*
  57. * Atributos
  58. */
  59. // Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
  60. private static final String SCOPE = "https://www.googleapis.com/auth/gmail.compose";
  61. private static final String APP_NAME = "eu***l";
  62. // Email address of the user, or "me" can be used to represent the currently authorized user.
  63. private static final String USER = "eu***@gmail.com";
  64. // Path to the client_secret.json file downloaded from the Developer Console
  65. private static final String CLIENT_SECRET_PATH = "../app-root/data/eu***.json";
  66.  
  67. private static GoogleClientSecrets clientSecrets;
  68.  
  69.  
  70. /*
  71. * Metodos
  72. */
  73.  
  74. public static Gmail init() throws IOException{
  75.  
  76. System.out.println("***Working Directory = " + System.getProperty("user.dir"));
  77.  
  78.  
  79. HttpTransport httpTransport = new NetHttpTransport();
  80. JsonFactory jsonFactory = new JacksonFactory();
  81.  
  82. clientSecrets = GoogleClientSecrets.load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));
  83.  
  84. // Allow user to authorize via url.
  85. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
  86. httpTransport, jsonFactory, clientSecrets, Arrays.asList(SCOPE))
  87. .setAccessType("online")
  88. .setApprovalPrompt("auto").build();
  89.  
  90. String code = "***";
  91.  
  92. // Generate Credential using retrieved code.
  93. GoogleTokenResponse response = flow.newTokenRequest(code)
  94. .setRedirectUri(GoogleOAuthConstants.OOB_REDIRECT_URI).execute();
  95. GoogleCredential credential = new GoogleCredential()
  96. .setFromTokenResponse(response);
  97.  
  98. // Create a new authorized Gmail API client
  99. return new Gmail.Builder(httpTransport, jsonFactory, credential)
  100. .setApplicationName(APP_NAME).build();
  101.  
  102.  
  103. }
  104.  
  105. /**
  106. * Create a MimeMessage using the parameters provided.
  107. *
  108. * @param to Email address of the receiver.
  109. * @param from Email address of the sender, the mailbox account.
  110. * @param subject Subject of the email.
  111. * @param bodyText Body text of the email.
  112. * @return MimeMessage to be used to send email.
  113. * @throws MessagingException
  114. */
  115. public static MimeMessage createEmail(String to, String from, String subject,
  116. String bodyText) throws MessagingException {
  117.  
  118. System.out.println("***Empezando a enviar email...");
  119.  
  120. Properties props = new Properties();
  121. Session session = Session.getDefaultInstance(props, null);
  122.  
  123. MimeMessage email = new MimeMessage(session);
  124. InternetAddress tAddress = new InternetAddress(to);
  125. InternetAddress fAddress = new InternetAddress(from);
  126.  
  127. email.setFrom(new InternetAddress(from));
  128. email.addRecipient(javax.mail.Message.RecipientType.TO,
  129. new InternetAddress(to));
  130. email.setSubject(subject);
  131. email.setText(bodyText);
  132. return email;
  133. }
  134.  
  135. /**
  136. * Create a Message from an email
  137. *
  138. * @param email Email to be set to raw of message
  139. * @return Message containing base64 encoded email.
  140. * @throws IOException
  141. * @throws MessagingException
  142. */
  143. public static Message createMessageWithEmail(MimeMessage email)
  144. throws MessagingException, IOException {
  145. ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  146. email.writeTo(bytes);
  147. String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
  148. Message message = new Message();
  149. message.setRaw(encodedEmail);
  150. return message;
  151. }
  152.  
  153. /**
  154. * Send an email from the user's mailbox to its recipient.
  155. *
  156. * @param service Authorized Gmail API instance.
  157. * @param userId User's email address. The special value "me"
  158. * can be used to indicate the authenticated user.
  159. * @param email Email to be sent.
  160. * @throws MessagingException
  161. * @throws IOException
  162. */
  163. public static void sendMessage(Gmail service, String userId, MimeMessage email)
  164. throws MessagingException, IOException {
  165. Message message = createMessageWithEmail(email);
  166. message = service.users().messages().send(userId, message).execute();
  167.  
  168. System.out.println("Message id: " + message.getId());
  169. System.out.println(message.toPrettyString());
  170. }
  171.  
  172. javax.mail.AuthenticationFailedException
  173. at javax.mail.Service.connect(Service.java:306)
  174. at javax.mail.Service.connect(Service.java:156)
  175. at main.java.model.EmailSenderService.sendEmail(EmailSenderService.java:86)
  176. at main.java.model.AccessManager.renewPassStepOne(AccessManager.java:234)
  177. at main.java.webService.UsuarioService.renewPassStepOne(UsuarioService.java:192)
  178. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  179. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
  180. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  181. at java.lang.reflect.Method.invoke(Method.java:606)
  182. at com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
  183. at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
  184. at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
  185. at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
  186. ...
  187.  
  188. MimeMessage msg = EmailSenderGmailApi.createEmail("ca***@gmail.com", "eu***@gmail.com", "test", "holaaaaa");
  189.  
  190. EmailSenderGmailApi.sendMessage(
  191. EmailSenderGmailApi.init(),
  192. "cap***@gmail.com",
  193. msg);
  194.  
  195. <dependency>
  196. <groupId>javax.mail</groupId>
  197. <artifactId>mail</artifactId>
  198. <version>1.4.7</version>
  199. </dependency>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement