Java Code Examples for org.springframework.mail.SimpleMailMessage#setTo()

The following examples show how to use org.springframework.mail.SimpleMailMessage#setTo() . 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: SpringMailSenderBackend.java    From haven-platform with Apache License 2.0 7 votes vote down vote up
@Override
public void send(MailMessage message) throws MailSenderException {
    SimpleMailMessage smm = new SimpleMailMessage();
    MailBody body = message.getBody();
    smm.setText(MailUtils.toPlainText(body));
    MailHead head = message.getHead();
    smm.setFrom(head.getFrom());
    smm.setReplyTo(head.getReplyTo());
    smm.setSubject(head.getSubject());
    smm.setTo(asArray(head.getTo()));
    smm.setCc(asArray(head.getCc()));
    smm.setBcc(asArray(head.getBcc()));
    smm.setSentDate(head.getSentDate());
    LOG.info("message to send {}", smm);
    mailSender.send(smm);
}
 
Example 2
Source File: MailerImpl.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
    * Construct and a send simple email message from a Mail Message.
    * 
    * @param message
    *            the Mail Message
 * @throws MessagingException 
    */
@Override
      @SuppressWarnings("unchecked")
public void sendEmail(MailMessage message) throws MessagingException {
       
       // Construct a simple mail message from the Mail Message
       SimpleMailMessage smm = new SimpleMailMessage();
       smm.setTo( (String[])message.getToAddresses().toArray(new String[message.getToAddresses().size()]) );
       smm.setBcc( (String[])message.getBccAddresses().toArray(new String[message.getBccAddresses().size()]) );
       smm.setCc( (String[])message.getCcAddresses().toArray(new String[message.getCcAddresses().size()]) );
       smm.setSubject(message.getSubject());
       smm.setText(message.getMessage());
       smm.setFrom(message.getFromAddress());

       try {
       	if ( LOG.isDebugEnabled() ) {
       		LOG.debug( "sendEmail() - Sending message: " + smm.toString() );
       	}
           mailSender.send(smm);
       }
       catch (Exception e) {
       	LOG.error("sendEmail() - Error sending email.", e);
		throw new RuntimeException(e);
       }
   }
 
Example 3
Source File: EmailAction.java    From spring-boot-examples with Apache License 2.0 6 votes vote down vote up
@PostMapping(value = "simple")
public String sendSimpleMsg(String msg, String email) {
    if (StringUtils.isEmpty(msg) || StringUtils.isEmpty(email)) {
        return "请输入要发送消息和目标邮箱";
    }

    try {
        SimpleMailMessage mail = new SimpleMailMessage();
        mail.setFrom(sendName);
        mail.setTo(email);
        mail.setSubject("这是一封简单邮件");
        mail.setText(msg);
        mailSender.send(mail);
        return "发送成功";
    } catch (Exception ex) {
        ex.printStackTrace();
        return "发送失败:" + ex.getMessage();
    }
}
 
Example 4
Source File: EmailUtil.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
public void sendSimpleMail(String to, HttpServletRequest request) {
    SimpleMailMessage message = new SimpleMailMessage();
    //设定邮件参数
    //发送者
    message.setFrom(username);
    //接收者
    message.setTo(to);
    //主题
    message.setSubject("修改pre系统用户邮箱");
    //邮件内容
    // 验证码
    String code = PreUtil.codeGen(4);
    message.setText("【Pre系统】" + ",验证码:" + code + "。" + "你正在使用邮箱验证码修改功能,该验证码仅用于身份验证,请勿透露给他人使用");
    // 发送邮件
    javaMailSender.send(message);
    request.getSession().setAttribute(PreConstant.RESET_MAIL, code.toLowerCase());
}
 
Example 5
Source File: SendOrderConfirmationEmailAdvice.java    From jpetstore-kubernetes with Apache License 2.0 5 votes vote down vote up
public void afterReturning(Object returnValue, Method m, Object[] args, Object target) throws Throwable {
	Order order = (Order) args[0];
	Account account = ((PetStoreFacade) target).getAccount(order.getUsername());

	// don't do anything if email address is not set
	if (account.getEmail() == null || account.getEmail().length() == 0) {
		return;
	}

	StringBuffer text = new StringBuffer();
	text.append("Dear ").append(account.getFirstName()).append(' ').append(account.getLastName());
	text.append(", thank your for your order from JPetStore. Please note that your order number is ");
	text.append(order.getOrderId());

	SimpleMailMessage mailMessage = new SimpleMailMessage();
	mailMessage.setTo(account.getEmail());
	mailMessage.setFrom(this.mailFrom);
	mailMessage.setSubject(this.subject);
	mailMessage.setText(text.toString());
	try {
		this.mailSender.send(mailMessage);
	}
	catch (MailException ex) {
		// just log it and go on
		logger.warn("An exception occured when trying to send email", ex);
	}
}
 
Example 6
Source File: FeedbackControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void submitErrorWhileSendingMail() throws Exception {
  List<String> adminEmails = Collections.singletonList("[email protected]");
  when(userService.getSuEmailAddresses()).thenReturn(adminEmails);
  when(appSettings.getRecaptchaIsEnabled()).thenReturn(true);
  when(reCaptchaService.validate("validCaptcha")).thenReturn(true);
  SimpleMailMessage expected = new SimpleMailMessage();
  expected.setTo("[email protected]");
  expected.setCc("[email protected]");
  expected.setReplyTo("[email protected]");
  expected.setSubject("[feedback-app123] Feedback form");
  expected.setText("Feedback from First Last ([email protected]):\n\n" + "Feedback.\nLine two.");
  doThrow(new MailSendException("ERRORRR!")).when(mailSender).send(expected);
  mockMvcFeedback
      .perform(
          MockMvcRequestBuilders.post(FeedbackController.URI)
              .param("name", "First Last")
              .param("subject", "Feedback form")
              .param("email", "[email protected]")
              .param("feedback", "Feedback.\nLine two.")
              .param("recaptcha", "validCaptcha"))
      .andExpect(status().isOk())
      .andExpect(view().name("view-feedback"))
      .andExpect(model().attribute("feedbackForm", hasProperty("submitted", equalTo(false))))
      .andExpect(
          model()
              .attribute(
                  "feedbackForm",
                  hasProperty(
                      "errorMessage",
                      equalTo(
                          "Unfortunately, we were unable to send the mail containing "
                              + "your feedback. Please contact the administrator."))));
  verify(reCaptchaService, times(1)).validate("validCaptcha");
}
 
Example 7
Source File: DemoController.java    From seed with Apache License 2.0 5 votes vote down vote up
@GetMapping("/mail")
public CommResult mail(){
    //发送一封简单的邮件
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    simpleMailMessage.setFrom(this.mailFrom);
    simpleMailMessage.setTo("[email protected]");
    simpleMailMessage.setSubject("下午开会准时参加");
    simpleMailMessage.setText("15点26楼会议室");
    this.javaMailSender.send(simpleMailMessage);
    //发送一封复杂的邮件
    //注意addInline()里面的"huiyi"要与"cid:huiyi"一致
    //注意addAttachment()方法用于添加附件
    try{
        MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(this.mailFrom);
        helper.setTo("[email protected]");
        helper.setSubject("请查收会议纪要");
        helper.setText("<html><body><span style='color:#F00'>会议截图如下,完整图片见附件。</span><br><img src=\\\"cid:huiyi\\\" ></body></html>", true);
        helper.addInline("huiyi", new FileSystemResource(new File("E:\\Jadyer\\Stripes.jpg")));
        helper.addAttachment("会议纪要完整图片.jpg", new FileSystemResource(new File("E:\\Jadyer\\Fedora13.jpg")));
        this.javaMailSender.send(mimeMessage);
    }catch(MessagingException e){
        return CommResult.fail(CodeEnum.SYSTEM_BUSY.getCode(), "邮件发送失败,堆栈轨迹如下:"+ JadyerUtil.extractStackTrace(e));
    }
    return CommResult.success();
}
 
Example 8
Source File: MailServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 发送文本邮件
 *
 * @param to      收件人地址
 * @param subject 邮件主题
 * @param content 邮件内容
 * @param cc      抄送地址
 */
@Override
public void sendSimpleMail(String to, String subject, String content, String... cc) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    if (ArrayUtil.isNotEmpty(cc)) {
        message.setCc(cc);
    }
    mailSender.send(message);
}
 
Example 9
Source File: FeedbackControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
void submitAuthenticationErrorWhileSendingMail() throws Exception {
  List<String> adminEmails = Collections.singletonList("[email protected]");
  when(userService.getSuEmailAddresses()).thenReturn(adminEmails);
  when(appSettings.getRecaptchaIsEnabled()).thenReturn(true);
  when(reCaptchaService.validate("validCaptcha")).thenReturn(true);
  SimpleMailMessage expected = new SimpleMailMessage();
  expected.setTo("[email protected]");
  expected.setCc("[email protected]");
  expected.setReplyTo("[email protected]");
  expected.setSubject("[feedback-app123] Feedback form");
  expected.setText("Feedback from First Last ([email protected]):\n\n" + "Feedback.\nLine two.");
  doThrow(new MailAuthenticationException("ERRORRR!")).when(mailSender).send(expected);
  mockMvcFeedback
      .perform(
          MockMvcRequestBuilders.post(FeedbackController.URI)
              .param("name", "First Last")
              .param("subject", "Feedback form")
              .param("email", "[email protected]")
              .param("feedback", "Feedback.\nLine two.")
              .param("recaptcha", "validCaptcha"))
      .andExpect(status().isOk())
      .andExpect(view().name("view-feedback"))
      .andExpect(model().attribute("feedbackForm", hasProperty("submitted", equalTo(false))))
      .andExpect(
          model()
              .attribute(
                  "feedbackForm",
                  hasProperty(
                      "errorMessage",
                      equalTo(
                          "Unfortunately, we were unable to send the mail containing "
                              + "your feedback. Please contact the administrator."))));
  verify(reCaptchaService, times(1)).validate("validCaptcha");
}
 
Example 10
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void failedSimpleMessage() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	simpleMessage1.setTo("[email protected]");
	simpleMessage1.setSubject("fail");
	SimpleMailMessage simpleMessage2 = new SimpleMailMessage();
	simpleMessage2.setTo("[email protected]");

	try {
		sender.send(simpleMessage1, simpleMessage2);
	}
	catch (MailSendException ex) {
		ex.printStackTrace();
		assertEquals("host", sender.transport.getConnectedHost());
		assertEquals("username", sender.transport.getConnectedUsername());
		assertEquals("password", sender.transport.getConnectedPassword());
		assertTrue(sender.transport.isCloseCalled());
		assertEquals(1, sender.transport.getSentMessages().size());
		assertEquals(new InternetAddress("[email protected]"), sender.transport.getSentMessage(0).getAllRecipients()[0]);
		assertEquals(1, ex.getFailedMessages().size());
		assertEquals(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		Object subEx = ex.getFailedMessages().values().iterator().next();
		assertTrue(subEx instanceof MessagingException);
		assertEquals("failed", ((MessagingException) subEx).getMessage());
	}
}
 
Example 11
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void javaMailSenderWithSimpleMessages() throws MessagingException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	simpleMessage1.setTo("[email protected]");
	SimpleMailMessage simpleMessage2 = new SimpleMailMessage();
	simpleMessage2.setTo("[email protected]");
	sender.send(simpleMessage1, simpleMessage2);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());

	assertEquals(2, sender.transport.getSentMessages().size());
	MimeMessage sentMessage1 = sender.transport.getSentMessage(0);
	List<Address> tos1 = Arrays.asList(sentMessage1.getRecipients(Message.RecipientType.TO));
	assertEquals(1, tos1.size());
	assertEquals("[email protected]", ((InternetAddress) tos1.get(0)).getAddress());
	MimeMessage sentMessage2 = sender.transport.getSentMessage(1);
	List<Address> tos2 = Arrays.asList(sentMessage2.getRecipients(Message.RecipientType.TO));
	assertEquals(1, tos2.size());
	assertEquals("[email protected]", ((InternetAddress) tos2.get(0)).getAddress());
}
 
Example 12
Source File: EmailBuilder.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * 发送简单邮件
 * @param from 发件人
 * @param to 收件人
 * @param subject 主题
 * @param text 正文
 */
public void sendSimpleEmail(String from, String to, String subject, String text){
    SimpleMailMessage message = new SimpleMailMessage();//消息构造器
    message.setFrom(from);//发件人
    message.setTo(to);//收件人
    message.setSubject(subject);//主题
    message.setText(text);//正文
    this.send(message);
}
 
Example 13
Source File: MailSenderUtil.java    From DrivingAgency with MIT License 5 votes vote down vote up
public void sendSimpleMail(String to, String subject, String content) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    try {
        mailSender.send(message);
        log.info("简单邮件已经发送。");
    } catch (Exception e) {
        log.error("发送简单邮件时发⽣异常!", e);
        throw new ParamException("邮件发送失败");
    }
}
 
Example 14
Source File: MailServiceImpl.java    From Jantent with MIT License 5 votes vote down vote up
/**
 * 发送简单邮件
 *
 * @param to
 * @param subject
 * @param content
 */
@Override
public void sendSimpleEmail(String to,String subject,String content) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(mailFrom);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    mailSender.send(message);
}
 
Example 15
Source File: MailService.java    From eds-starter6-jpa with Apache License 2.0 5 votes vote down vote up
@Async
public void sendSimpleMessage(String to, String subject, String text) {
	SimpleMailMessage mailMessage = new SimpleMailMessage();
	mailMessage.setFrom(this.defaultSender);
	mailMessage.setTo(to);
	mailMessage.setText(text);
	mailMessage.setSubject(subject);
	this.mailSender.send(mailMessage);
}
 
Example 16
Source File: MailMessageNotifier.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Send mail messages.
 *
 * @param simpleMessages
 */
@Override
public void send(GenericNotifyMessage msg) {
    String mailMsgType = msg.getParameterAsString(KEY_MAILMSG_TYPE, "simple");
    switch (mailMsgType) {
        case KEY_MAILMSG_VALUE_SIMPLE:
            SimpleMailMessage simpleMsg = new SimpleMailMessage();
            // Add "<>" symbol to send out?
            /*
             * Preset from account, otherwise it would be wrong: 501 mail from
             * address must be same as authorization user.
             */
            simpleMsg.setFrom(config.getUsername() + "<" + config.getUsername() + ">");
            simpleMsg.setTo(msg.getToObjects().stream().map(to -> to = to + "<" + to + ">").collect(toList()).toArray(new String[]{}));
            simpleMsg.setSubject(msg.getParameterAsString(KEY_MAILMSG_SUBJECT, "Super Devops Messages"));
            simpleMsg.setSentDate(msg.getParameter(KEY_MSG_SENDDATE, new Date()));
            simpleMsg.setBcc(safeList(msg.getParameter(KEY_MAILMSG_BCC)).toArray(new String[]{}));
            simpleMsg.setCc(safeList(msg.getParameter(KEY_MAILMSG_CC)).toArray(new String[]{}));
            simpleMsg.setReplyTo(msg.getParameter(KEY_MAILMSG_REPLYTO));
            simpleMsg.setText(config.getResolvedMessage(msg.getTemplateKey(), msg.getParameters()));

            mailSender.send(simpleMsg);
            break;
        case KEY_MAILMSG_VALUE_MIME: // TODO implements!!!
            log.warn("No implements MimeMailMessage!!!");
            break;
        default:
            throw new UnsupportedOperationException(format("No supported mail message type of %s", mailMsgType));
    }

}
 
Example 17
Source File: MailService.java    From springbootexamples with Apache License 2.0 5 votes vote down vote up
/**
 * 发送简单的邮件信息
 * @param toMail
 * @param subject
 * @param content
 */
public void sendSimpleMail(String toMail,String subject,String content) {
	SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
	simpleMailMessage.setFrom(formMail);
	simpleMailMessage.setTo(toMail);
	simpleMailMessage.setSubject(subject);
	simpleMailMessage.setText(content);
	try {
		sender.send(simpleMailMessage);
		logger.info("发送给"+toMail+"简单邮件已经发送。 subject:"+subject);
	} catch (Exception e) {
           logger.info("发送给"+toMail+"send mail error subject:"+subject);
           e.printStackTrace();
	}
}
 
Example 18
Source File: MailTests.java    From SpringBootUnity with MIT License 5 votes vote down vote up
@Test
public void sendSimpleMail() throws Exception {

    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom("[email protected]");
    message.setTo("[email protected]");
    message.setSubject("主题:简单邮件");
    message.setText("测试邮件内容");

    mailSender.send(message);
}
 
Example 19
Source File: MailServiceImpl.java    From DouBiNovel with Apache License 2.0 5 votes vote down vote up
@Override
public void sendSimpleMail(String to, String subject, String content) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    try {
        mailSender.send(message);
        logger.info("简单邮件已经发送。");
    } catch (Exception e) {
        logger.error("发送简单邮件时发生异常!", e);
    }
}
 
Example 20
Source File: JavaMailSenderTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test
public void javaMailSenderWithSimpleMessage() throws MessagingException, IOException {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("host");
	sender.setPort(30);
	sender.setUsername("username");
	sender.setPassword("password");

	SimpleMailMessage simpleMessage = new SimpleMailMessage();
	simpleMessage.setFrom("[email protected]");
	simpleMessage.setReplyTo("[email protected]");
	simpleMessage.setTo("[email protected]");
	simpleMessage.setCc("[email protected]", "[email protected]");
	simpleMessage.setBcc("[email protected]", "[email protected]");
	Date sentDate = new GregorianCalendar(2004, 1, 1).getTime();
	simpleMessage.setSentDate(sentDate);
	simpleMessage.setSubject("my subject");
	simpleMessage.setText("my text");
	sender.send(simpleMessage);

	assertEquals("host", sender.transport.getConnectedHost());
	assertEquals(30, sender.transport.getConnectedPort());
	assertEquals("username", sender.transport.getConnectedUsername());
	assertEquals("password", sender.transport.getConnectedPassword());
	assertTrue(sender.transport.isCloseCalled());

	assertEquals(1, sender.transport.getSentMessages().size());
	MimeMessage sentMessage = sender.transport.getSentMessage(0);
	List<Address> froms = Arrays.asList(sentMessage.getFrom());
	assertEquals(1, froms.size());
	assertEquals("[email protected]", ((InternetAddress) froms.get(0)).getAddress());
	List<Address> replyTos = Arrays.asList(sentMessage.getReplyTo());
	assertEquals("[email protected]", ((InternetAddress) replyTos.get(0)).getAddress());
	List<Address> tos = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.TO));
	assertEquals(1, tos.size());
	assertEquals("[email protected]", ((InternetAddress) tos.get(0)).getAddress());
	List<Address> ccs = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.CC));
	assertEquals(2, ccs.size());
	assertEquals("[email protected]", ((InternetAddress) ccs.get(0)).getAddress());
	assertEquals("[email protected]", ((InternetAddress) ccs.get(1)).getAddress());
	List<Address> bccs = Arrays.asList(sentMessage.getRecipients(Message.RecipientType.BCC));
	assertEquals(2, bccs.size());
	assertEquals("[email protected]", ((InternetAddress) bccs.get(0)).getAddress());
	assertEquals("[email protected]", ((InternetAddress) bccs.get(1)).getAddress());
	assertEquals(sentDate.getTime(), sentMessage.getSentDate().getTime());
	assertEquals("my subject", sentMessage.getSubject());
	assertEquals("my text", sentMessage.getContent());
}