org.springframework.mail.SimpleMailMessage Java Examples

The following examples show how to use org.springframework.mail.SimpleMailMessage. 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: MailServiceTest.java    From Mario with Apache License 2.0 7 votes vote down vote up
/**
 * 多附件邮件测试
 * 
 * @throws MessagingException
 * @throws InterruptedException
 * @throws IOException
 */
@Test
public void testSendMailMultiFiles() throws MessagingException, InterruptedException,
        IOException {
    SimpleMailMessage message = buildSimpleMessage();
    String[] files = new String[] { EMAIL_ATTACHMENT, EMAIL_ATTACHMENT };
    mimeMailService.sendMailFiles(message, files);

    greenMail.waitForIncomingEmail(2000, 1);

    MimeMessage[] msgs = greenMail.getReceivedMessages();
    MimeMultipart mimeMultipart = (MimeMultipart) msgs[0].getContent();

    assertEquals(1, msgs.length);
    assertEquals(MAIL_MESSAGE_FROM, msgs[0].getFrom()[0].toString());
    assertEquals(MAIL_MESSAGE_SUBJECT, msgs[0].getSubject());
    assertEquals(3, mimeMultipart.getCount());//multipart个数
    assertTrue(GreenMailUtil.getBody(mimeMultipart.getBodyPart(0)).trim()
            .contains(MAIL_MESSAGE_CONTEXT));
    assertEquals("Hello,i am a attachment.", GreenMailUtil
            .getBody(mimeMultipart.getBodyPart(1)).trim());
    assertEquals("Hello,i am a attachment.", GreenMailUtil
            .getBody(mimeMultipart.getBodyPart(2)).trim());
}
 
Example #2
Source File: MailServiceTest.java    From Mario with Apache License 2.0 6 votes vote down vote up
/**
 * MimeMessage格式邮件发送
 * 
 * @throws Exception
 */
@Test
public void testSendMail() throws Exception {
    SimpleMailMessage message = buildSimpleMessage();
    mimeMailService.sendMail(message);

    greenMail.waitForIncomingEmail(2000, 1);

    MimeMessage[] msgs = greenMail.getReceivedMessages();
    MimeMultipart mimeMultipart = (MimeMultipart) msgs[0].getContent();

    assertEquals(1, msgs.length);
    assertEquals(MAIL_MESSAGE_FROM, msgs[0].getFrom()[0].toString());
    assertEquals(MAIL_MESSAGE_SUBJECT, msgs[0].getSubject());
    assertTrue(GreenMailUtil.getBody(mimeMultipart.getBodyPart(0)).trim()
            .contains(MAIL_MESSAGE_CONTEXT));
}
 
Example #3
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void failedMailServerClose() throws Exception {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost("");
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(0, ex.getFailedMessages().size());
	}
}
 
Example #4
Source File: JavaMailSenderFacadeTest.java    From fake-smtp-server with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSendSimpleMessageWhenMailSystemIsAvailable() {
    var javaMailSender = mock(JavaMailSender.class);
    var logger = mock(Logger.class);
    var message = mock(SimpleMailMessage.class);

    var sut = new JavaMailSenderFacade();
    sut.setJavaMailSender(javaMailSender);
    sut.setLogger(logger);

    sut.send(message);

    verify(javaMailSender).send(message);
    verifyNoMoreInteractions(javaMailSender);
    verifyNoInteractions(logger);
}
 
Example #5
Source File: EmailNotificationService.java    From jsflight with Apache License 2.0 6 votes vote down vote up
private SimpleMailMessage getMessageTemplate(MongoDbScenario scenario, Throwable ex)
{
    Settings settings = settingsService.getSettings();

    SimpleMailMessage mailMessage = new SimpleMailMessage();
    mailMessage.setFrom(settings.getSmtpFrom());
    mailMessage.setTo(settings.getAlarmEmails().split(","));
    String body = "";
    if (ex != null)
    {
        body += ex.toString() + "\n\n\n";
    }
    body += new JSONObject((scenario)).toString(4);
    mailMessage.setText(body);
    return mailMessage;
}
 
Example #6
Source File: MailController.java    From spring-boot-study with MIT License 6 votes vote down vote up
/**
 * 发送文本标题 文本内容
 * */
@GetMapping("/sendMail")
public String sendMail(){
    try{

        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sendUser);
        message.setTo("[email protected]");
        message.setSubject("主题邮件");
        message.setText("邮件内容");
        mailSender.send(message);
        return "success";
    }catch (Exception e){
        e.printStackTrace();
        return "fail";
    }
}
 
Example #7
Source File: EmailMessageSender.java    From magic-starter with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 处理简单邮件类型
 *
 * @param message 邮件内容
 * @return boolean
 */
private boolean processSimpleEmail(EmailMessage message) {
	// 注意邮件发送可能出现异常,注意catch
	try {
		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
		simpleMailMessage.setFrom("\"" + message.getFrom() + "\" <" + username + ">");
		simpleMailMessage.setTo(ArrayUtil.toArray(message.getTos(), String.class));
		simpleMailMessage.setSubject(message.getSubject());
		simpleMailMessage.setText(message.getContent());

		// 设置抄送人列表
		if (CollUtil.isEmpty(message.getCcs())) {
			simpleMailMessage.setCc(ArrayUtil.toArray(message.getCcs(), String.class));
		}
		mailSender.send(simpleMailMessage);
		return true;
	} catch (Exception e) {
		log.error("简单邮件发送异常!", e);
		return false;
	}
}
 
Example #8
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 #9
Source File: FeedbackController.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
/** Creates a MimeMessage based on a FeedbackForm. */
@SuppressWarnings("java:S3457") // do not use platform specific line ending
private SimpleMailMessage createFeedbackMessage(FeedbackForm form) {
  SimpleMailMessage message = new SimpleMailMessage();
  message.setTo(userService.getSuEmailAddresses().toArray(new String[] {}));
  if (form.hasEmail()) {
    message.setCc(form.getEmail());
    message.setReplyTo(form.getEmail());
  } else {
    message.setReplyTo("[email protected]");
  }
  String appName = appSettings.getTitle();
  message.setSubject(String.format("[feedback-%s] %s", appName, form.getSubject()));
  message.setText(String.format("Feedback from %s:\n\n%s", form.getFrom(), form.getFeedback()));
  return message;
}
 
Example #10
Source File: JavaMailSenderTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void failedMailServerConnect() {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost(null);
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(1, ex.getFailedMessages().size());
		assertSame(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		assertSame(ex.getCause(), ex.getFailedMessages().values().iterator().next());
	}
}
 
Example #11
Source File: MailTest.java    From SpringBootLearn with Apache License 2.0 6 votes vote down vote up
/**
 * 发送简单邮件
 */
@Test
public void sendSimpleMail() {
    SimpleMailMessage message = new SimpleMailMessage();
    //设定邮件参数
    //发送者
    message.setFrom(username);
    //接收者
    message.setTo("[email protected]");
    //主题
    message.setSubject("测试主题");
    //邮件内容
    message.setText("测试内容");
    // 发送邮件
    javaMailSender.send(message);
}
 
Example #12
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 #13
Source File: SimpleEmailServiceMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void testSendMultipleMailsWithExceptionWhileSending() throws Exception {
	AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class);
	SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(
			emailService);

	SimpleMailMessage firstMessage = createSimpleMailMessage();
	firstMessage.setBcc("[email protected]");

	SimpleMailMessage failureMail = createSimpleMailMessage();
	when(emailService.sendEmail(ArgumentMatchers.isA(SendEmailRequest.class)))
			.thenReturn(new SendEmailResult())
			.thenThrow(new AmazonClientException("error"))
			.thenReturn(new SendEmailResult());

	SimpleMailMessage thirdMessage = createSimpleMailMessage();

	try {
		mailSender.send(firstMessage, failureMail, thirdMessage);
		fail("Exception expected due to error while sending mail");
	}
	catch (MailSendException e) {
		assertThat(e.getFailedMessages().size()).isEqualTo(1);
		assertThat(e.getFailedMessages().containsKey(failureMail)).isTrue();
	}
}
 
Example #14
Source File: MailServiceTest.java    From Mario with Apache License 2.0 6 votes vote down vote up
/**
 * 一个附件的邮件测试
 * 
 * @throws MessagingException
 * @throws InterruptedException
 * @throws IOException
 */
@Test
public void testSendMailFiles() throws MessagingException, InterruptedException, IOException {
    SimpleMailMessage message = buildSimpleMessage();
    String[] files = new String[] { EMAIL_ATTACHMENT };
    mimeMailService.sendMailFiles(message, files);

    greenMail.waitForIncomingEmail(2000, 1);

    MimeMessage[] msgs = greenMail.getReceivedMessages();
    MimeMultipart mimeMultipart = (MimeMultipart) msgs[0].getContent();

    assertEquals(1, msgs.length);
    assertEquals(MAIL_MESSAGE_FROM, msgs[0].getFrom()[0].toString());
    assertEquals(MAIL_MESSAGE_SUBJECT, msgs[0].getSubject());
    assertEquals(2, mimeMultipart.getCount());//multipart个数
    assertTrue(GreenMailUtil.getBody(mimeMultipart.getBodyPart(0)).trim()
            .contains(MAIL_MESSAGE_CONTEXT));
    assertEquals("Hello,i am a attachment.", GreenMailUtil
            .getBody(mimeMultipart.getBodyPart(1)).trim());
}
 
Example #15
Source File: ProgressImplTest.java    From molgenis with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
void testMailFailed() {
  jobExecution.setFailureEmail("[email protected],[email protected]");
  progress.start();
  progress.status("Working....");
  Exception ex = new IllegalArgumentException("blah");
  progress.failed("blah", ex);
  System.out.println(jobExecution.getLog());
  assertTrue(jobExecution.getLog().contains("- Execution started." + System.lineSeparator()));
  assertTrue(jobExecution.getLog().contains("- Working...." + System.lineSeparator()));
  assertTrue(jobExecution.getLog().contains("- Failed"));
  assertTrue(jobExecution.getLog().contains(ex.getMessage()));

  SimpleMailMessage mail = new SimpleMailMessage();
  mail.setTo(new String[] {"[email protected]", "[email protected]"});
  mail.setSubject("Annotator job failed.");
  mail.setText(jobExecution.getLog());
  verify(mailSender).send(mail);
}
 
Example #16
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 #17
Source File: MailServiceImpl.java    From yunsleLive_room with MIT License 6 votes vote down vote up
@Override
public boolean sendMail(String address, String content) {
    try {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("[email protected]");
        message.setTo(address);
        message.setSubject("主题:忘记密码");
        message.setText("Hi,你好。这是你的密码:"+content+" 请注意密码安全,及时修改!");
        mailSender.send(message);
        return true;
    } catch (Exception e) {
        System.err.println("sendMail错误:"+e);
        return false;
    }

}
 
Example #18
Source File: SendMail.java    From shark with Apache License 2.0 6 votes vote down vote up
public SendMail() {
	mailBean = new MailBean();
	mailSender = new JavaMailSenderImpl();
	mailSender.setPort(mailBean.getPORT());
	mailSender.setHost(mailBean.getHOST());
	mailSender.setUsername(mailBean.getUSERNAME());
	mailSender.setPassword(mailBean.getPASSWORD());
	Properties properties = new Properties();
	properties.setProperty("mail.smtp.auth", "true");
	mailSender.setJavaMailProperties(properties);
	mailMessage = new SimpleMailMessage();
	mailMessage.setFrom(mailBean.getFROM());
	mailMessage.setTo(mailBean.getTO());
	mailMessage.setSubject(mailBean.getSUBJECT());
	GetUserInfo getUserInfo = new GetUserInfo();
	mailMessage.setText("[version]:" + LoadVersion.getVersion() + "\n[javaVersion]:" + getUserInfo.getJavaVersion()
			+ "\n[osName]:" + getUserInfo.getOsName() + "\n[jvmName]:" + getUserInfo.getJvmName() + "\n[address]:"
			+ getUserInfo.getAddress() + "\n[hostName]:" + getUserInfo.getHostname() + "\n[startTime]:"
			+ getUserInfo.getStartTime());
}
 
Example #19
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void failedMailServerConnect() throws Exception {
	MockJavaMailSender sender = new MockJavaMailSender();
	sender.setHost(null);
	sender.setUsername("username");
	sender.setPassword("password");
	SimpleMailMessage simpleMessage1 = new SimpleMailMessage();
	try {
		sender.send(simpleMessage1);
		fail("Should have thrown MailSendException");
	}
	catch (MailSendException ex) {
		// expected
		ex.printStackTrace();
		assertTrue(ex.getFailedMessages() != null);
		assertEquals(1, ex.getFailedMessages().size());
		assertSame(simpleMessage1, ex.getFailedMessages().keySet().iterator().next());
		assertSame(ex.getCause(), ex.getFailedMessages().values().iterator().next());
	}
}
 
Example #20
Source File: EmailServiceImpl.java    From tutorials with MIT License 5 votes vote down vote up
public void sendSimpleMessage(String to, String subject, String text) {
    try {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(NOREPLY_ADDRESS);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(text);

        emailSender.send(message);
    } catch (MailException exception) {
        exception.printStackTrace();
    }
}
 
Example #21
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 #22
Source File: MailEventNotifier.java    From earth-frost with Apache License 2.0 5 votes vote down vote up
@Override
protected void doNotify(Event event) {

  JobInfo jobInfo = Container.get().getJobRepository()
      .findJobInfoById(event.getData().getJobId());
  if (jobInfo == null) {
    return;
  }

  Map<String, Object> attrs = MoreObjects.mapOf("event", event, "job", jobInfo);

  String subjectVal = ENGINE.render(DEFAULT_SUBJECT, attrs);
  String textVal = ENGINE.render(DEFAULT_TEXT, attrs);

  SimpleMailMessage message = new SimpleMailMessage();

  String[] mails = jobInfo.getNotifyMails();
  String[] dest;
  if (mails != null) {
    dest = Arrays.copyOf(mails, mails.length + to.length);
    System.arraycopy(to, 0, dest, mails.length, to.length);
  } else {
    dest = to;
  }
  message.setTo(dest);
  message.setFrom(from);
  message.setSubject(subjectVal);
  message.setText(textVal);
  message.setCc(cc);

  sender.send(message);
}
 
Example #23
Source File: MailServiceImpl.java    From nimrod with MIT License 5 votes vote down vote up
private void sendSimpleMailMessage(String from, String[] toArray, String subject, String text) {
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    simpleMailMessage.setFrom(from);
    simpleMailMessage.setTo(toArray);
    simpleMailMessage.setSubject(subject);
    simpleMailMessage.setText(text);
    javaMailSender.send(simpleMailMessage);
}
 
Example #24
Source File: SimpleEmailServiceMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private SimpleMailMessage createSimpleMailMessage() {
	SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
	simpleMailMessage.setFrom("[email protected]");
	simpleMailMessage.setTo("[email protected]");
	simpleMailMessage.setSubject("message subject");
	simpleMailMessage.setText("message body");
	return simpleMailMessage;
}
 
Example #25
Source File: TestMailSender.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void send(SimpleMailMessage msg) throws MailException {
    String[] tos = msg.getTo();
    for(String to: tos) {
        mailbox.computeIfAbsent(to, (k) -> new CopyOnWriteArrayList<>()).add(msg);
        log.info("Receive for {}, \n message: {} ", to, msg);
    }
}
 
Example #26
Source File: SendEmailService.java    From sitemonitoring-production with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void sendEmail(JavaMailSenderImpl javaMailSenderImpl, String from, String to, String subject, String body) {
	SimpleMailMessage mailMessage = new SimpleMailMessage();
	mailMessage.setFrom(from);
	mailMessage.setTo(to);
	mailMessage.setSubject(subject);
	mailMessage.setText(body);
	javaMailSenderImpl.send(mailMessage);
}
 
Example #27
Source File: EmailSender.java    From Spring-Boot-Examples with MIT License 5 votes vote down vote up
void sendEmail(String to, String from, String title, String content) {
    SimpleMailMessage mail = new SimpleMailMessage();
    mail.setTo(to);
    mail.setFrom(from);
    mail.setSubject(title);
    mail.setText(content);
    javaMailSender.send(mail);
}
 
Example #28
Source File: MailSender.java    From sso with MIT License 5 votes vote down vote up
@Override
public void send(MailInformative informative) throws ValidateSenderException {
    SimpleMailMessage message = new SimpleMailMessage();

    message.setFrom(informative.getFromMail());//发送者.
    message.setTo(informative.getToMail());//接收者.
    message.setSubject(informative.getSubject());//邮件主题.
    message.setText(informative.getContent());//邮件内容.

    mailSender.send(message);//发送邮件
}
 
Example #29
Source File: TokenDeliverySystemEmailTests.java    From QuizZz with MIT License 5 votes vote down vote up
@Before
public void before() {
	messageSource = mock(MessageSource.class);
	token = mock(TokenModel.class);
	mailServer = mock(JavaMailSender.class);

	tokenDeliverySystem = new TokenDeliverySystemEmail(messageSource, mailServer);

	captor = ArgumentCaptor.forClass(SimpleMailMessage.class);

	user.setId(1l);
}
 
Example #30
Source File: JavaMailSenderTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public void testJavaMailSenderWithSimpleMessages() throws MessagingException, IOException {
	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());
}