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 File: AbstractMailService.java    From halo with 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 File: EmailConfiguration.java    From tutorials with 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 #3
Source File: MailConfig.java    From restfiddle with 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 #4
Source File: MailNotifierTest.java    From Moss with 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 #5
Source File: MailUtil.java    From PhrackCTF-Platform-Personal with 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 #6
Source File: EmailConfiguration.java    From activiti6-boot2 with 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 #7
Source File: SimpleEmailServiceJavaMailSenderTest.java    From spring-cloud-aws with 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 File: AbstractMailService.java    From halo with 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 #9
Source File: SmtpMailer.java    From alf.io with 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 #10
Source File: MailServerInfo.java    From lemon with Apache License 2.0 5 votes vote down vote up
public JavaMailSender getJavaMailSender() {
    if (javaMailSender == null) {
        this.updateJavaMailSender();
    }

    return javaMailSender;
}
 
Example #11
Source File: MailService.java    From tutorials with 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 #12
Source File: JavaMailUtils.java    From seppb with 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 File: JavaMailUtils.java    From seppb with 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 #14
Source File: MailService.java    From alchemy with 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 File: MailService.java    From Spring-5.0-Projects with 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 File: MailService.java    From Full-Stack-Development-with-JHipster with 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 File: MailTool.java    From maintain with 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 File: SimpleEmailServiceJavaMailSenderTest.java    From spring-cloud-aws with 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 File: DefaultExUrlProvider.java    From tx-lcn with 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 File: MailService.java    From 21-points with 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 File: MailAutoConfigurationTest.java    From genie with 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 File: SimpleEmailServiceJavaMailSenderTest.java    From spring-cloud-aws with 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 File: MailSenderAutoConfigurationTest.java    From spring-cloud-aws with 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 File: SpringMailTestConfiguration.java    From konker-platform with 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 File: EmailSender.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Resource(name = CubaMailSender.NAME)
public void setMailSender(JavaMailSender mailSender) {
    this.mailSender = mailSender;
}
 
Example #26
Source File: EmailNotificationServiceImpl.java    From podcastpedia-web with MIT License 4 votes vote down vote up
public void setMailSender(JavaMailSender mailSender) {
	this.mailSender = mailSender;
}
 
Example #27
Source File: EmailServiceImpl.java    From hermes with Apache License 2.0 4 votes vote down vote up
public JavaMailSender getJavaMailSender() {
	return javaMailSender;
}
 
Example #28
Source File: WaltzEmailer.java    From waltz with Apache License 2.0 4 votes vote down vote up
@Autowired
public WaltzEmailer(JavaMailSender mailSender) {
    this.mailSender = mailSender;
}
 
Example #29
Source File: MailSenderFactoryTest.java    From spring-cloud-connectors with Apache License 2.0 4 votes vote down vote up
public JavaMailSender getMockConnector() {
	return mockConnector;
}
 
Example #30
Source File: ScooldEmailer.java    From scoold with Apache License 2.0 4 votes vote down vote up
public ScooldEmailer(JavaMailSender mailSender) {
	this.mailSender = mailSender;
}