org.springframework.mail.javamail.JavaMailSender Java Examples

The following examples show how to use org.springframework.mail.javamail.JavaMailSender. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: halo   Author: halo-dev   File: AbstractMailService.java    License: GNU General Public License v3.0 8 votes vote down vote up
/**
 * Test connection with email server.
 */
@Override
public void testConnection() {
    JavaMailSender javaMailSender = getMailSender();
    if (javaMailSender instanceof JavaMailSenderImpl) {
        JavaMailSenderImpl mailSender = (JavaMailSenderImpl) javaMailSender;
        try {
            mailSender.testConnection();
        } catch (MessagingException e) {
            throw new EmailException("无法连接到邮箱服务器,请检查邮箱配置.[" + e.getMessage() + "]", e);
        }
    }
}
 
Example #2
Source Project: Moss   Author: SpringCloud   File: MailNotifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    repository = mock(InstanceRepository.class);
    when(repository.find(instance.getId())).thenReturn(Mono.just(instance));

    sender = mock(JavaMailSender.class);
    when(sender.createMimeMessage()).thenAnswer(args -> new MimeMessage(Session.getInstance(new Properties())));

    SpringTemplateEngine templateEngine = new SpringTemplateEngine();
    ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
    resolver.setTemplateMode(TemplateMode.HTML);
    resolver.setCharacterEncoding(StandardCharsets.UTF_8.name());
    templateEngine.addTemplateResolver(resolver);

    notifier = new MailNotifier(sender, repository, templateEngine);
    notifier.setTo(new String[]{"[email protected]"});
    notifier.setCc(new String[]{"[email protected]"});
    notifier.setFrom("SBA <[email protected]>");
    notifier.setBaseUrl("http://localhost:8080");
    notifier.setTemplate("/META-INF/spring-boot-admin-server/mail/status-changed.html");
}
 
Example #3
Source Project: tutorials   Author: eugenp   File: EmailConfiguration.java    License: MIT License 6 votes vote down vote up
@Bean
public JavaMailSender getJavaMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(587);
    
    mailSender.setUsername("[email protected]");
    mailSender.setPassword("password");
    
    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "false");
    props.put("mail.debug", "true");
    
    return mailSender;
}
 
Example #4
Source Project: restfiddle   Author: AnujaK   File: MailConfig.java    License: Apache License 2.0 6 votes vote down vote up
@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;
   }
 
Example #5
Source Project: alf.io   Author: alfio-event   File: SmtpMailer.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static JavaMailSender toMailSender(Map<ConfigurationKeys, ConfigurationManager.MaybeConfiguration> conf) {
    JavaMailSenderImpl r = new CustomJavaMailSenderImpl();
    r.setDefaultEncoding("UTF-8");

    r.setHost(conf.get(SMTP_HOST).getRequiredValue());
    r.setPort(Integer.parseInt(conf.get(SMTP_PORT).getRequiredValue()));
    r.setProtocol(conf.get(SMTP_PROTOCOL).getRequiredValue());
    r.setUsername(conf.get(SMTP_USERNAME).getValueOrDefault(null));
    r.setPassword(conf.get(SMTP_PASSWORD).getValueOrDefault(null));

    String properties = conf.get(SMTP_PROPERTIES).getValueOrDefault(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;
}
 
Example #6
Source Project: halo   Author: halo-dev   File: AbstractMailService.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get from-address.
 *
 * @param javaMailSender java mail sender.
 * @return from-name internet address
 * @throws UnsupportedEncodingException throws when you give a wrong character encoding
 */
private synchronized InternetAddress getFromAddress(@NonNull JavaMailSender javaMailSender) throws UnsupportedEncodingException {
    Assert.notNull(javaMailSender, "Java mail sender must not be null");

    if (StringUtils.isBlank(this.cachedFromName)) {
        // set personal name
        this.cachedFromName = optionService.getByPropertyOfNonNull(EmailProperties.FROM_NAME).toString();
    }

    if (javaMailSender instanceof JavaMailSenderImpl) {
        // get user name(email)
        JavaMailSenderImpl mailSender = (JavaMailSenderImpl) javaMailSender;
        String username = mailSender.getUsername();

        // build internet address
        return new InternetAddress(username, this.cachedFromName, mailSender.getDefaultEncoding());
    }

    throw new UnsupportedOperationException("Unsupported java mail sender: " + javaMailSender.getClass().getName());
}
 
Example #7
Source Project: spring-cloud-aws   Author: spring-cloud   File: SimpleEmailServiceJavaMailSenderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
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) {
		assertThat(e.getMessage().startsWith("Could not parse raw MIME content"))
				.isTrue();
		assertThat(e.getCause().getCause()).isSameAs(ioException);
	}
}
 
Example #8
Source Project: activiti6-boot2   Author: dingziyang   File: EmailConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public JavaMailSender javaMailSender() {
    JavaMailSenderImpl sender = new JavaMailSenderImpl();
    
    boolean isEmailEnabled = env.getProperty("email.enabled", Boolean.class, false);
    if (isEmailEnabled) {
        sender.setHost(env.getRequiredProperty("email.host"));
        sender.setPort(env.getRequiredProperty("email.port", Integer.class));
    } 
    
    Boolean useCredentials = env.getProperty("email.useCredentials", Boolean.class);
    if (Boolean.TRUE.equals(useCredentials)) {
        sender.setUsername(env.getProperty("email.username"));
        sender.setPassword(env.getProperty("email.password"));
    }
    
    Boolean emailTLS = env.getProperty("email.tls", Boolean.class);
    if (emailTLS != null) {
      sender.getJavaMailProperties().setProperty("mail.smtp.starttls.enable", emailTLS.toString());
    }
    
    return sender;
}
 
Example #9
Source Project: PhrackCTF-Platform-Personal   Author: zjlywjh001   File: MailUtil.java    License: Apache License 2.0 6 votes vote down vote up
@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();
	}
}
 
Example #10
Source Project: lemon   Author: xuhuisheng   File: MailServerInfo.java    License: Apache License 2.0 5 votes vote down vote up
public JavaMailSender getJavaMailSender() {
    if (javaMailSender == null) {
        this.updateJavaMailSender();
    }

    return javaMailSender;
}
 
Example #11
Source Project: seppb   Author: purang-fintech   File: JavaMailUtils.java    License: MIT License 5 votes vote down vote up
/**
 * 最基础的邮件发送接口(包含:标题、内容)
 *
 * @param mailDTO
 * @throws MessagingException
 */
public static boolean sendMail(@NonNull final MailDTO mailDTO) throws InterruptedException, ExecutionException,MessagingException {
    ApplicationContext appCtx = CommonFactory.getApplicationContext();
    JavaMailSender javaMailSender = appCtx.getBean(JavaMailSender.class);
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    buildMimeMessage(mailDTO, mimeMessage);
    if (mailDTO.isFailRetry()) {
        return failRetrySendMail(mailDTO, javaMailSender, mimeMessage);
    }
    return sendMail(javaMailSender, mimeMessage);
}
 
Example #12
Source Project: seppb   Author: purang-fintech   File: JavaMailUtils.java    License: MIT License 5 votes vote down vote up
/**
 * @param mailDTO
 * @param javaMailSender
 * @param mimeMessage
 * @return
 * @throws Exception
 */
private static boolean failRetrySendMail(@NonNull MailDTO mailDTO, JavaMailSender javaMailSender, MimeMessage mimeMessage)
        throws InterruptedException, ExecutionException {
    if (mailDTO.isBlock()) {
        return asynchronousMailFailRetry(mailDTO, javaMailSender, mimeMessage);

    } else {
        synchronizedMailFailRetry(mailDTO, javaMailSender, mimeMessage);
        return false;
    }
}
 
Example #13
Source Project: tutorials   Author: eugenp   File: MailService.java    License: MIT License 5 votes vote down vote up
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender,
        MessageSource messageSource, SpringTemplateEngine templateEngine) {

    this.jHipsterProperties = jHipsterProperties;
    this.javaMailSender = javaMailSender;
    this.messageSource = messageSource;
    this.templateEngine = templateEngine;
}
 
Example #14
Source Project: alchemy   Author: binglind   File: MailService.java    License: Apache License 2.0 5 votes vote down vote up
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender,
        MessageSource messageSource, SpringTemplateEngine templateEngine) {

    this.jHipsterProperties = jHipsterProperties;
    this.javaMailSender = javaMailSender;
    this.messageSource = messageSource;
    this.templateEngine = templateEngine;
}
 
Example #15
Source Project: Spring-5.0-Projects   Author: PacktPublishing   File: MailService.java    License: MIT License 5 votes vote down vote up
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender,
        MessageSource messageSource, SpringTemplateEngine templateEngine) {

    this.jHipsterProperties = jHipsterProperties;
    this.javaMailSender = javaMailSender;
    this.messageSource = messageSource;
    this.templateEngine = templateEngine;
}
 
Example #16
Source Project: Full-Stack-Development-with-JHipster   Author: PacktPublishing   File: MailService.java    License: MIT License 5 votes vote down vote up
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender,
        MessageSource messageSource, SpringTemplateEngine templateEngine) {

    this.jHipsterProperties = jHipsterProperties;
    this.javaMailSender = javaMailSender;
    this.messageSource = messageSource;
    this.templateEngine = templateEngine;
}
 
Example #17
Source Project: maintain   Author: zhaopei8948   File: MailTool.java    License: MIT License 5 votes vote down vote up
public static void sendMail(JavaMailSender mailSender, String from, String to, String subject, String text) {
	try {
		
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(from);// 发送者.
		message.setTo(to);// 接收者.
		message.setSubject(subject);// 邮件主题.
		message.setText(text);// 邮件内容.

		mailSender.send(message);// 发送邮件
		
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example #18
Source Project: spring-cloud-aws   Author: spring-cloud   File: SimpleEmailServiceJavaMailSenderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testSendMimeMessage() throws MessagingException {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);

	JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService);
	ArgumentCaptor<SendRawEmailRequest> request = ArgumentCaptor
			.forClass(SendRawEmailRequest.class);
	when(emailService.sendRawEmail(request.capture()))
			.thenReturn(new SendRawEmailResult().withMessageId("123"));
	MimeMessage mimeMessage = createMimeMessage();
	mailSender.send(mimeMessage);
	assertThat(mimeMessage.getMessageID()).isEqualTo("123");
}
 
Example #19
Source Project: tx-lcn   Author: codingapi   File: DefaultExUrlProvider.java    License: Apache License 2.0 5 votes vote down vote up
public DefaultExUrlProvider(@Autowired(required = false) JavaMailSender javaMailSender,
                            @Autowired(required = false) MailProperties mailProperties,
                            @Autowired TxManagerConfig txManagerConfig) {
    this.javaMailSender = javaMailSender;
    this.mailProperties = mailProperties;
    Objects.requireNonNull(txManagerConfig, "tx-manager config can't be null.");

    // ujued's email can be ignored.
    if (Objects.isNull(javaMailSender)) {
        if (txManagerConfig.getExUrl().contains("[email protected]")) {
            txManagerConfig.setExUrlEnabled(false);
        }
    }
}
 
Example #20
Source Project: 21-points   Author: mraible   File: MailService.java    License: Apache License 2.0 5 votes vote down vote up
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender,
        MessageSource messageSource, SpringTemplateEngine templateEngine) {

    this.jHipsterProperties = jHipsterProperties;
    this.javaMailSender = javaMailSender;
    this.messageSource = messageSource;
    this.templateEngine = templateEngine;
}
 
Example #21
Source Project: genie   Author: Netflix   File: MailAutoConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Confirm we can get a mail service implementation using JavaMailSender.
 */
@Test
void canGetMailServiceImpl() {
    final JavaMailSender javaMailSender = Mockito.mock(JavaMailSender.class);
    final MailProperties properties = new MailProperties();
    properties.setFromAddress("[email protected]");
    Assertions.assertThat(
        new MailAutoConfiguration().getJavaMailSenderMailService(javaMailSender, properties)
    ).isNotNull();
}
 
Example #22
Source Project: spring-cloud-aws   Author: spring-cloud   File: SimpleEmailServiceJavaMailSenderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testSendMultipleMimeMessages() throws Exception {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);

	JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService);

	when(emailService.sendRawEmail(ArgumentMatchers.isA(SendRawEmailRequest.class)))
			.thenReturn(new SendRawEmailResult().withMessageId("123"));
	mailSender.send(createMimeMessage(), createMimeMessage());
	verify(emailService, times(2))
			.sendRawEmail(ArgumentMatchers.isA(SendRawEmailRequest.class));
}
 
Example #23
Source Project: spring-cloud-aws   Author: spring-cloud   File: MailSenderAutoConfigurationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void mailSender_MailSenderWithJava_configuresJavaMailSender() {
	this.contextRunner.run(context -> {
		assertThat(context.getBean(MailSender.class)).isNotNull();
		assertThat(context.getBean(JavaMailSender.class)).isNotNull();
		assertThat(context.getBean(JavaMailSender.class))
				.isSameAs(context.getBean(MailSender.class));
	});
}
 
Example #24
Source Project: konker-platform   Author: KonkerLabs   File: SpringMailTestConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
  public JavaMailSender javaMailSender() {
  	JavaMailSenderImpl mock = mock(JavaMailSenderImpl.class);
when(mock.createMimeMessage()).thenReturn(mock(MimeMessage.class));

  	return mock;
  }
 
Example #25
Source Project: beihu-boot   Author: beihu-stack   File: AbstarctMailSender.java    License: Apache License 2.0 4 votes vote down vote up
public JavaMailSender getJavaMailSender() {
    return javaMailSender;
}
 
Example #26
Source Project: spring-cloud-connectors   Author: spring-cloud   File: MailSenderFactory.java    License: Apache License 2.0 4 votes vote down vote up
public MailSenderFactory(String serviceId, ServiceConnectorConfig serviceConnectorConfiguration) {
	super(serviceId, JavaMailSender.class, serviceConnectorConfiguration);
}
 
Example #27
Source Project: datax-web   Author: WeiYe-Jing   File: JobAdminConfig.java    License: MIT License 4 votes vote down vote up
public JavaMailSender getMailSender() {
    return mailSender;
}
 
Example #28
Source Project: nextreports-server   Author: nextreports   File: DistributionContext.java    License: Apache License 2.0 4 votes vote down vote up
public void setMailSender(JavaMailSender mailSender) {
    this.mailSender = mailSender;
}
 
Example #29
Source Project: cf-butler   Author: pacphi   File: NotifierConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Bean
public EmailNotifier javaMailNotifier(JavaMailSender javaMailSender) {
    return new JavaMailNotifier(javaMailSender);
}
 
Example #30
Source Project: website   Author: Paperight   File: EmailTransformer.java    License: GNU Affero General Public License v3.0 4 votes vote down vote up
public void setEmailSender(JavaMailSender emailSender) {
	this.emailSender = emailSender;
}