@Bean public JavaMailSender javaMailService() { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); if (this.auth) { javaMailSender.setUsername(this.username); javaMailSender.setPassword(this.password); } Properties properties = new Properties(); properties.setProperty("mail.transport.protocol", this.protocol); properties.setProperty("mail.smtp.auth", Boolean.toString(this.auth)); properties.setProperty("mail.smtp.starttls.enable", Boolean.toString(this.starttls)); properties.setProperty("mail.debug", Boolean.toString(this.debug)); properties.setProperty("mail.smtp.host", this.host); properties.setProperty("mail.smtp.port", Integer.toString(this.port)); properties.setProperty("mail.smtp.ssl.trust", this.trust); javaMailSender.setJavaMailProperties(properties); return javaMailSender; }
@Async public void sendPasswordResetMail(String target,String reseturl,JavaMailSender javaMailSender) throws InterruptedException { try { MimeMessage mimeMsg = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, false, "utf-8"); String content = (String) PropertyPlaceholder.getProperty("mail.template"); content = content.replace("{reseturl}", reseturl); helper.setText(content, true); helper.setTo(new String[]{target}); String title = (String) PropertyPlaceholder.getProperty("mail.title"); helper.setSubject(title); String authormail = (String) PropertyPlaceholder.getProperty("mail.sendfrom"); String authorname = (String) PropertyPlaceholder.getProperty("mail.sendname"); helper.setFrom(authormail,authorname); javaMailSender.send(mimeMsg); log.info("Password Reset Mail has been send to "+target); } catch(Exception e) { e.printStackTrace(); } }
@Bean public JavaMailSender mailSender() { JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost(this.properties.getHost()); sender.setPort(this.properties.getPort()); sender.setUsername(this.properties.getUsername()); sender.setPassword(this.properties.getPassword()); sender.setProtocol(this.properties.getProtocol()); sender.setDefaultEncoding(this.properties.getDefaultEncoding().name()); // extra properties if (!this.properties.getProperties().isEmpty()) { Properties mailProperties = new Properties(); mailProperties.putAll(this.properties.getProperties()); sender.setJavaMailProperties(mailProperties); } return sender; }
/** * Return the {@link JavaMailSender} built from the given node. * * @param node * The node holding the SMTP configuration. * @return the {@link JavaMailSender} built from the given node. */ @CacheResult(cacheName = "plugin-data") public JavaMailSender getMailSender(@CacheKey final String node) { final JavaMailSenderImpl mail = new JavaMailSenderImpl(); final Map<String, String> parameters = pvResource.getNodeParameters(node); mail.setUsername(parameters.get(PARAMETER_USER)); mail.setPassword(parameters.get(PARAMETER_PASSWORD)); mail.setHost(parameters.get(PARAMETER_HOST)); mail.setPort(Optional.ofNullable(parameters.get(PARAMETER_PORT)).map(Integer::valueOf).orElse(125)); mail.setDefaultEncoding("UTF-8"); final Properties properties = new Properties(); properties.put("mail.smtp.auth", Boolean.TRUE); properties.put("mail.smtp.starttls.enable", Boolean.TRUE); properties.put("mail.smtp.quitwait", Boolean.FALSE); properties.put("mail.smtp.socketFactory.fallback", Boolean.FALSE); mail.setJavaMailProperties(properties); return mail; }
private static JavaMailSender build(MailConfigSource config) { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setDefaultEncoding(StandardCharsets.UTF_8.name()); mailSender.setHost(config.mailServer().getHost()); mailSender.setPort(config.mailServer().getPort()); JProps mailProps = new JProps(mailSender.getJavaMailProperties()); configureTransport(config, mailProps); config.username().ifPresent( u -> configureAuthentication(config, u, mailSender, mailProps)); if (MailProtocol.smtps.equals(config.protocol())) { configureTls(config, mailProps); } return mailSender; }
@Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); Properties mailProperties = new Properties(); mailProperties.put("mail.smtp.auth", auth); mailProperties.put("mail.smtp.starttls.enable", starttls); mailSender.setJavaMailProperties(mailProperties); mailSender.setHost(host); mailSender.setPort(port); mailSender.setProtocol(protocol); mailSender.setUsername(username); mailSender.setPassword(password); return mailSender; }
@Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); Properties mailProperties = new Properties(); mailProperties.put("mail.smtp.auth", auth); mailProperties.put("mail.smtp.starttls.enable", starttls); mailProperties.put("mail.smtp.starttls.required", startlls_required); mailProperties.put("mail.smtp.socketFactory.port", socketPort); mailProperties.put("mail.smtp.debug", debug); mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); mailProperties.put("mail.smtp.socketFactory.fallback", fallback); mailSender.setJavaMailProperties(mailProperties); mailSender.setHost(host); mailSender.setPort(port); mailSender.setProtocol(protocol); mailSender.setUsername(username); mailSender.setPassword(password); return mailSender; }
@Async public void mailTo(String[] targetuser,String title,String content,JavaMailSender javaMailSender) {//邮件功能 try { MimeMessage mimeMsg = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, false, "utf-8"); helper.setText(content, true); helper.setBcc(targetuser); helper.setSubject(title); String authormail = (String) PropertyPlaceholder.getProperty("mail.sendfrom"); String authorname = (String) PropertyPlaceholder.getProperty("mail.sendname"); helper.setFrom(authormail,authorname); javaMailSender.send(mimeMsg); log.info("Mail send to "+Arrays.toString(targetuser)); } catch(Exception e) { e.printStackTrace(); } }
@Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(config.getSmtpHost()); mailSender.setPort(config.getSmtpPort()); mailSender.setProtocol(config.getSmtpProtocol()); mailSender.setUsername(config.getSmtpUsername()); mailSender.setPassword(config.getSmtpPassword()); mailSender.setDefaultEncoding("UTF-8"); if ("smtps".equalsIgnoreCase(config.getSmtpProtocol())) { Properties mailProperties = new Properties(); mailProperties.setProperty("mail.smtps.auth", "true"); mailProperties.setProperty("mail.smtp.ssl.enable", "true"); mailProperties.setProperty("mail.transport.protocol", "smtps"); mailProperties.setProperty("mail.debug", "true"); mailProperties.setProperty("mail.mime.charset", "utf8"); mailSender.setJavaMailProperties(mailProperties); } return mailSender; }
@Autowired public CaptchaService(UserInfoValidator userInfoValidator, LsPushProperties lsPushProperties, JavaMailSender mailSender, TemplateEngine templateEngine, ObjectMapper objectMapper, UserRepository userRepo) { mUserInfoValidator = userInfoValidator; serverName = lsPushProperties.getServerName(); serverUrl = lsPushProperties.getServerUrl(); serverEmail = lsPushProperties.getServerEmail(); mMailSender = mailSender; mTemplateEngine = templateEngine; mObjectMapper = objectMapper; mUserRepo = userRepo; mAuthCodeMap = CacheBuilder.newBuilder() .initialCapacity(100) .maximumSize(500) .expireAfterWrite(30, TimeUnit.MINUTES) .build(); mStringFunnel = (Funnel<String>) (from, into) -> into.putString(from, StandardCharsets.UTF_8); resetBloomFilter(); }
public JavaMailSender getMailSender() { if (mailSender == null) { final JavaMailSenderImpl impl = new JavaMailSenderImpl(); impl.setHost(smtpServer); impl.setPort(smtpPort); final Properties properties = new Properties(); if (StringUtils.isNotEmpty(smtpUsername)) { // Use authentication properties.setProperty("mail.smtp.auth", "true"); impl.setUsername(smtpUsername); impl.setPassword(smtpPassword); } if (smtpUseTLS) { properties.setProperty("mail.smtp.starttls.enable", "true"); } impl.setJavaMailProperties(properties); mailSender = impl; } return mailSender; }
public EmailService(JavaMailSender mailSender, String supportEmail, String personalName) throws UnsupportedEncodingException { if(mailSender==null) { throw new IllegalArgumentException("EmailService constructor contains a null JavaMailSender argument"); } if(supportEmail==null) { throw new IllegalArgumentException("EmailService constructor contains a null String argument"); } Address[] temp = null; try { temp = new Address[] {new InternetAddress(supportEmail, personalName)}; } catch (IllegalArgumentException e) { LOGGER.error(e); } this.senderAddresses = temp; this.mailSender = mailSender; }
/** * Try to perform the lookup of the email service. This is called during * configuration so that any failure happens at a useful, predictable time. */ @PostConstruct public void tryLookup() { if (!isAvailable()) { log.warn("no mail support; disabling email dispatch"); sender = null; return; } try { if (sender instanceof JavaMailSender) ((JavaMailSender) sender).createMimeMessage(); } catch (Throwable t) { log.warn("sender having problems constructing messages; " + "disabling...", t); sender = null; } }
/** * Creates a {@link JavaMailSender} to send an email using gmail * @param userCode * @param password * @return */ public static JavaMailSender create(final UserCode userCode, final Password password) { Properties javaMailProps = SpringJavaMailSenderImplDecorator.createJavaMailProperties(); javaMailProps.put("mail.smtp.auth",true); javaMailProps.put("mail.smtp.starttls.enable",true); JavaMailSenderImpl outMailSender = new SpringJavaMailSenderImplDecorator(); outMailSender.setHost("smtp.gmail.com"); outMailSender.setPort(587); outMailSender.setUsername(userCode.asString()); outMailSender.setPassword(password.asString()); // see https://support.google.com/accounts/answer/185833 outMailSender.setJavaMailProperties(javaMailProps); return outMailSender; }
@Override @SuppressWarnings("resource") protected void configure() { R01F.initSystemEnv(); bind(MailManager.class).toInstance(new MailManager()); ApplicationContext springAppContext = new AnnotationConfigApplicationContext(SpringConfiguration.class); bind(BeanFactory.class).toInstance(springAppContext); // Bind spring managed beans // (remember that spring binds the @Bean-annotated method with the method name) bind(JavaMailSender.class).toProvider(SpringIntegration.fromSpring(JavaMailSender.class, "mailSender")); bind(MailMessage.class).toProvider(SpringIntegration.fromSpring(MailMessage.class, "mailMessageTemplate")); bind(VelocityEngine.class).toProvider(SpringIntegration.fromSpring(VelocityEngine.class, "velocityEngine")); }
/** * Gets the mail sender. * * @return the mail sender */ private JavaMailSender getMailSender() { final JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); final ApplicationConfiguration smtpHostConfig = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_HOST, SMTP_HOST, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_HOST, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_HOST, "localhost"); final ApplicationConfiguration smtpPort = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_PORT, SMTP_PORT, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_PORT, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_PORT, "587"); final ApplicationConfiguration smtpUsername = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_USERNAME, SMTP_USERNAME, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_USERNAME, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_USERNAME, "username"); final ApplicationConfiguration smtpPassword = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_SECRET, SMTP_SECRET, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_SECRET, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_SECRET, "password"); final ApplicationConfiguration smtpAuth = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_AUTH, SMTP_AUTH, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_AUTH, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_AUTH, "true"); final ApplicationConfiguration smtpStartTlsEnable = applicationConfigurationService.checkValueOrLoadDefault(EMAIL_CONFIGURATION_SMTP_STARTTLS_ENABLE, SMTP_STARTTLS_ENABLE, ConfigurationGroup.EXTERNAL_SERVICES, EmailServiceImpl.class.getSimpleName(), SMTP_STARTTLS_ENABLE, RESPONSIBLE_FOR_SENDING_EMAIL, APPLICATION_EMAIL_SMTP_STARTTLS_ENABLE, "true"); javaMailSender.setHost(smtpHostConfig.getPropertyValue()); javaMailSender.setPort(Integer.parseInt(smtpPort.getPropertyValue())); javaMailSender.setUsername(smtpUsername.getPropertyValue()); javaMailSender.setPassword(smtpPassword.getPropertyValue()); final Properties javaMailProperties = new Properties(); javaMailProperties.setProperty(MAIL_SMTP_AUTH, smtpAuth.getPropertyValue()); javaMailProperties.setProperty(MAIL_SMTP_STARTTLS_ENABLE, smtpStartTlsEnable.getPropertyValue()); javaMailSender.setJavaMailProperties(javaMailProperties); return javaMailSender; }
@Bean @Autowired @ConditionalOnProperty(name = MAIL_SERVICE_PROPERTY, havingValue = "realEmailService") public JavaMailSender mailSender(@Value("${mail.host}") String host, @Value("${mail.port}") String port, @Value("${mail.username}") String username, @Value("${mail.password}") String password) { JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl(); javaMailSender.setHost(host); javaMailSender.setPort(Integer.valueOf(port)); javaMailSender.setUsername(username); javaMailSender.setPassword(password); return javaMailSender; }
public EmailServiceImpl(FreeMarkerConfigurer freemarkerConfig, MessageSource messageSource, JavaMailSender javaMailSender, String baseURL, String defaultReplyTo, String sendToOM, String sendToVRK, int invitationExpirationDays, String testSendTo, boolean testConsoleOutput) { this.freemarkerConfig = freemarkerConfig; this.messageSource = messageSource; this.javaMailSender = javaMailSender; this.baseURL = baseURL; this.defaultReplyTo = defaultReplyTo; this.invitationExpirationDays = invitationExpirationDays; this.sendToOM = sendToOM; this.sendToVRK = sendToVRK; if (Strings.isNullOrEmpty(testSendTo)) { this.testSendTo = null; } else { this.testSendTo = testSendTo; } this.testConsoleOutput = testConsoleOutput; }
@Bean public JavaMailSender javaMailSender() { String smtpServer = env.getRequiredProperty(PropertyNames.emailSmtpServer); Integer smtpServerPort = env.getProperty(PropertyNames.emailSmtpServerPort, Integer.class, null); String smtpUserName = env.getProperty(PropertyNames.emailSmtpUsername); String smtpPassword = env.getProperty(PropertyNames.emailSmtpPassword); JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost(smtpServer); sender.setUsername(smtpUserName); sender.setPassword(smtpPassword); if (smtpServerPort != null) { // otherwise use default port sender.setPort(smtpServerPort); } return sender; }
@Bean public JavaMailSender javaMailSender() { Properties javaMailProperties = new Properties(); javaMailProperties.put("mail.smtp.auth", smtpAuth); javaMailProperties.put("mail.smtp.starttls.enable", smtpStartTLS); javaMailProperties.put("mail.smtp.host", smtpHost); javaMailProperties.put("mail.smtp.port", smtpPort); JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setJavaMailProperties(javaMailProperties); if (smtpAuth) { sender.setUsername(smtpUser); sender.setPassword(smtpPassword); } return sender; }
@Bean public JavaMailSender javaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); Properties mailProperties = new Properties(); mailSender.setProtocol(env.getProperty("mail.protocol")); mailSender.setHost(env.getProperty("mail.host")); mailSender.setPort(Integer.parseInt(env.getProperty("mail.port"))); mailSender.setUsername(env.getProperty("mail.username")); mailSender.setPassword(env.getProperty("mail.password")); mailProperties.put("mail.smtp.auth", env.getProperty("mail.smtp.auth")); mailProperties.put("mail.smtp.starttls.enable", env.getProperty("mail.smtp.starttls.enable")); mailProperties.put("mail.smtp.debug", env.getProperty("mail.smtp.debug")); mailProperties.put("mail.smtp.socketFactory.port", "465"); mailProperties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); mailProperties.put("mail.smtps.ssl.trust", env.getProperty("mail.smtps.ssl.trust")); mailProperties.put("mail.smtps.ssl.checkserveridentity", env.getProperty("mail.smtps.ssl.checkserveridentity")); mailSender.setJavaMailProperties(mailProperties); return mailSender; }
@Test public void testCreateMimeMessageWithExceptionInInputStream() throws Exception { InputStream inputStream = mock(InputStream.class); AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService); IOException ioException = new IOException("error"); when(inputStream.read(ArgumentMatchers.any(byte[].class), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())).thenThrow(ioException); try { mailSender.createMimeMessage(inputStream); fail("MailPreparationException expected due to error while creating mail"); } catch (MailParseException e) { assertTrue(e.getMessage().startsWith("Could not parse raw MIME content")); assertSame(ioException, e.getCause().getCause()); } }
@Test public void testSendMultipleMailsWithException() throws Exception { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService); MimeMessage failureMail = createMimeMessage(); when(emailService.sendRawEmail(ArgumentMatchers.isA(SendRawEmailRequest.class))). thenReturn(new SendRawEmailResult()). thenThrow(new AmazonClientException("error")). thenReturn(new SendRawEmailResult()); try { mailSender.send(createMimeMessage(), failureMail, createMimeMessage()); fail("Exception expected due to error while sending mail"); } catch (MailSendException e) { assertEquals(1, e.getFailedMessages().size()); assertTrue(e.getFailedMessages().containsKey(failureMail)); } }
private JavaMailSender toMailSender(Event event) { JavaMailSenderImpl r = new CustomJavaMailSenderImpl(); r.setDefaultEncoding("UTF-8"); r.setHost(configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_HOST))); r.setPort(Integer.valueOf(configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_PORT)))); r.setProtocol(configurationManager.getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_PROTOCOL))); r.setUsername(configurationManager.getStringConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_USERNAME), null)); r.setPassword(configurationManager.getStringConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_PASSWORD), null)); String properties = configurationManager.getStringConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), SMTP_PROPERTIES), null); if (properties != null) { try { Properties prop = PropertiesLoaderUtils.loadProperties(new EncodedResource(new ByteArrayResource( properties.getBytes(StandardCharsets.UTF_8)), "UTF-8")); r.setJavaMailProperties(prop); } catch (IOException e) { log.warn("error while setting the mail sender properties", e); } } return r; }
/** * Test case for the <code>dispatch()</code> method * of class <code>EmailDispatcher</code> * * @throws Exception if an error occurs during test */ public void testDispatchException() throws Exception { Map<String, Map<String, List<Commit>>> userCommits = new HashMap<String, Map<String, List<Commit>>>(); Map<String, Map<String, String>> userCommands = new HashMap<String, Map<String, String>>(); Mock messageMock = mock(MockableMimeMessage.class); messageMock.expects(once()).method("setContent").withAnyArguments().will(throwException(new MessagingException("unit test"))); Mock senderMock = mock(JavaMailSender.class); senderMock.expects(once()).method("createMimeMessage").withNoArguments().will(returnValue(messageMock.proxy())); MergeReport.setRequestorAddress("unit-test" + MergeReport.getMailDomain()); emailDispatcher.processString = TEST_STRING; emailDispatcher.userCommits = userCommits; emailDispatcher.userCommands = userCommands; emailDispatcher.sender = (JavaMailSender) senderMock.proxy(); try { emailDispatcher.dispatch(null); fail("should've thrown exception"); } catch (RuntimeException e) { assertEquals("Exception message not as expected.", "An error occurred while trying to send the email.", e.getMessage()); } }
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender, MessageSource messageSource, SpringTemplateEngine templateEngine) { this.jHipsterProperties = jHipsterProperties; this.javaMailSender = javaMailSender; this.messageSource = messageSource; this.templateEngine = templateEngine; }
/** * Constructor. * * @param javaMailSender The mail sender to use */ @Autowired public MailServiceImpl( @NotNull final JavaMailSender javaMailSender ) { this.javaMailSender = javaMailSender; }