Java Code Examples for org.springframework.mail.javamail.JavaMailSender#send()

The following examples show how to use org.springframework.mail.javamail.JavaMailSender#send() . 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: EmailServiceImpl.java    From Fame with MIT License 7 votes vote down vote up
/**
 * 发送邮件
 *
 * @param content 邮件内容(html)
 * @param to      收件人
 * @throws MessagingException
 */
private void sendEmail(String content, String to) throws MessagingException {
    String subject = optionService.get(OptionKeys.EMAIL_SUBJECT, FameConsts.DEFAULT_EMAIL_TEMPLATE_SUBJECT);
    String host = optionService.get(OptionKeys.EMAIL_HOST);
    Integer port = optionService.get(OptionKeys.EMAIL_PORT, 25);
    String username = optionService.get(OptionKeys.EMAIL_USERNAME);
    String password = optionService.get(OptionKeys.EMAIL_PASSWORD);

    JavaMailSender mailSender = (JavaMailSender) mailSender(host, port,
            username, password);
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
    helper.setFrom(username);
    helper.setTo(to);
    helper.setText(content, true);
    helper.setSubject(subject);
    mailSender.send(mimeMessage);
}
 
Example 2
Source File: MailUtil.java    From PhrackCTF-Platform-Team with Apache License 2.0 6 votes vote down vote up
@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();
	}
}
 
Example 3
Source File: MailUtil.java    From PhrackCTF-Platform-Personal with Apache License 2.0 6 votes vote down vote up
@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();
	}
}
 
Example 4
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 5
Source File: EmailSendMsgHandle.java    From jeecg-boot-with-activiti with MIT License 5 votes vote down vote up
@Override
public void SendMsg(String es_receiver, String es_title, String es_content) {
	JavaMailSender mailSender = (JavaMailSender) SpringContextUtils.getBean("mailSender");
	SimpleMailMessage message = new SimpleMailMessage();
	// 设置发送方邮箱地址
	message.setFrom(emailFrom);
	message.setTo(es_receiver);
	message.setSubject(es_title);
	message.setText(es_content);
	mailSender.send(message);

}
 
Example 6
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 7
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 8
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 9
Source File: JavaMailUtils.java    From seppb with MIT License 4 votes vote down vote up
/**
 * 同步发送邮件(不包含重试机制)
 */
public static boolean sendMail(JavaMailSender javaMailSender, MimeMessage message) {
    javaMailSender.send(message);
    return true;
}
 
Example 10
Source File: AbstractMailService.java    From halo with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Send mail template.
 *
 * @param callback mime message callback.
 */
protected void sendMailTemplate(@Nullable Callback callback) {
    if (callback == null) {
        log.info("Callback is null, skip to send email");
        return;
    }

    // check if mail is enable
    Boolean emailEnabled = optionService.getByPropertyOrDefault(EmailProperties.ENABLED, Boolean.class);

    if (!emailEnabled) {
        // If disabled
        log.info("Email has been disabled by yourself, you can re-enable it through email settings on admin page.");
        return;
    }

    // get mail sender
    JavaMailSender mailSender = getMailSender();
    printMailConfig();

    // create mime message helper
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage());

    try {
        // set from-name
        messageHelper.setFrom(getFromAddress(mailSender));
        // handle message set separately
        callback.handle(messageHelper);

        // get mime message
        MimeMessage mimeMessage = messageHelper.getMimeMessage();
        // send email
        mailSender.send(mimeMessage);

        log.info("Sent an email to [{}] successfully, subject: [{}], sent date: [{}]",
            Arrays.toString(mimeMessage.getAllRecipients()),
            mimeMessage.getSubject(),
            mimeMessage.getSentDate());
    } catch (Exception e) {
        throw new EmailException("邮件发送失败,请检查 SMTP 服务配置是否正确", e);
    }
}
 
Example 11
Source File: MailUtil.java    From PhrackCTF-Platform-Team with Apache License 2.0 4 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 12
Source File: BulkMailProcessorImpl.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void run() {

    final Map<String, Integer> exceptionsThresholdsByShop = new HashMap<>();

    Long lastFailedEmailId = null;
    Mail mail = mailService.findOldestMail(lastFailedEmailId);
    while (mail != null) {

        listener.notifyMessage("Preparing mail object {}/{} for {} with subject {}",
                mail.getMailId(), mail.getShopCode(), mail.getRecipients(), mail.getSubject());

        final String shopCode = mail.getShopCode();
        listener.notifyPing("Sending mail for " + shopCode);

        if (!exceptionsThresholdsByShop.containsKey(shopCode)) {
            exceptionsThresholdsByShop.put(shopCode, this.cycleExceptionsThreshold);
        }

        int exceptionsThreshold = exceptionsThresholdsByShop.get(shopCode);
        if (exceptionsThreshold <= 0) {
            lastFailedEmailId = mail.getMailId();
            listener.notifyMessage("Skipping send mail as exception threshold is exceeded for shop {}", shopCode);
        } else {

            final JavaMailSender javaMailSender = javaMailSenderFactory.getJavaMailSender(shopCode);
            if (javaMailSender == null) {
                listener.notifyMessage("No mail sender configured for {}", shopCode);
                lastFailedEmailId = mail.getMailId();
            } else {

                final MimeMessage mimeMessage = javaMailSender.createMimeMessage();

                boolean sent = false;
                try {
                    mailComposer.convertMessage(mail, mimeMessage);
                    javaMailSender.send(mimeMessage);
                    sent = true;
                    listener.count(SENT_COUNTER);
                    listener.notifyMessage("Sent mail to {} with subject {}", mail.getRecipients(), mail.getSubject());
                    mailService.delete(mail);
                } catch (Exception exp) {
                    LOG.error(Markers.alert(), "Unable to send mail " + mail.getMailId() + "/" + mail.getSubject() + " for shop " + shopCode, exp);
                    lastFailedEmailId = mail.getMailId();
                    exceptionsThresholdsByShop.put(shopCode, exceptionsThreshold - 1);
                    listener.count(ERROR_COUNTER);
                }

                if (sent && delayBetweenEmailsMs > 0) {
                    if (this.shutdown.get()) {
                        break; // we are shutting down
                    }
                    try {
                        Thread.sleep(delayBetweenEmailsMs);
                    } catch (InterruptedException e) {
                        // resume
                    }
                }
            }
        }

        mail = mailService.findOldestMail(lastFailedEmailId);

    }

    listener.notifyCompleted();
    listener.reset();

}
 
Example 13
Source File: SimpleEmailServiceJavaMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 3 votes vote down vote up
@Test
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) {
		assertThat(e.getFailedMessages().size()).isEqualTo(1);
		assertThat(e.getFailedMessages().containsKey(failureMail)).isTrue();
	}
}