Java Code Examples for org.springframework.mail.javamail.MimeMessageHelper#addTo()

The following examples show how to use org.springframework.mail.javamail.MimeMessageHelper#addTo() . 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: RegisterSystemListener.java    From cms with Apache License 2.0 6 votes vote down vote up
@Async
    @Order
    @EventListener(EmailEvent.class)
    public void emailListener(EmailEvent event) {
        MimeMessagePreparator mailMessage = mimeMessage -> {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);
            message.setFrom(from, fromName);
            for (String to : event.getTos()) {
                message.addTo(to);
            }
            message.setSubject(event.getSubject());
            message.setText(event.getContent(), true);
//            String html = "<html><body><h4>Hello,SpringBoot</h4><img src='cid:boot' /></body></html>";
//            mimeMessageHelper.setText(html, true);
            // 设置内嵌元素 cid,第一个参数表示内联图片的标识符,第二个参数标识资源引用
//            mimeMessageHelper.addInline("boot", new ClassPathResource("public/images/boot.png"));
            //添加附件,第一个参数表示添加到 Email 中附件的名称,第二个参数是图片资源
        };

        mailSender.send(mailMessage);
    }
 
Example 2
Source File: TestSendException.java    From smtp-connection-pool with Apache License 2.0 6 votes vote down vote up
@Test
public void testReturnedOnException() throws Exception {
  try (ClosableSmtpConnection connection = smtpConnectionPool.borrowObject()) {
    MimeMessage mimeMessage = new MimeMessage(connection.getSession());
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false);
    mimeMessageHelper.addTo("[email protected]");
    mimeMessageHelper.setFrom("[email protected]");
    mimeMessageHelper.setSubject("foo");
    mimeMessageHelper.setText("example", false);
    // We stop the server before we actually send the message
    stopServer();
    connection.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
    Assert.fail("The connection should fail since the server is stopped");
  } catch (MailSendException | MessagingException e) {
    // It should come here, but the connection should not be returned in the pool
  }
  Assert.assertEquals(1, smtpConnectionPool.getBorrowedCount());
  Assert.assertEquals(0, smtpConnectionPool.getDestroyedCount());
  Assert.assertEquals(1, smtpConnectionPool.getReturnedCount());
}
 
Example 3
Source File: MailServiceImpl.java    From olat with Apache License 2.0 6 votes vote down vote up
@Override
public void sendMailWithAttachments(final TemplateWithAttachmentMailTO template) throws MailException {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

            message.addTo(template.getToMailAddress());
            message.setFrom(template.getFromMailAddress());
            message.setSubject(template.getSubject());
            if (template.hasCcMailAddress()) {
                message.setCc(template.getCcMailAddress());
            }
            if (template.hasReplyTo()) {
                message.setReplyTo(template.getReplyTo());
            }

            // add attachments if any
            List<File> attachments = template.getAttachments();
            for (File file : attachments) {
                message.addAttachment(file.getName(), file);
            }

            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template.getTemplateLocation(), template.getTemplateProperties());
            message.setText(text, true);
            message.setValidateAddresses(true);
        }
    };
    this.mailSender.send(preparator);
}
 
Example 4
Source File: JobOutput.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void prepareEmail(MimeMessage mimeMessage, String subject, String emailAddresses) throws Exception {
	if (!CommonUtil.isEmptyString(emailAddresses)) {
		MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, getEmailEncoding());
		mimeMessageHelper.setSubject(subject);
		mimeMessageHelper.setText(output.toString());
		mimeMessageHelper.setFrom(Settings.getEmailExecFromAddress(), Settings.getEmailExecFromName());
		String[] addresses = emailAddressSeparatorRegexp.split(emailAddresses, -1);
		for (int i = 0; i < addresses.length; i++) {
			if (!CommonUtil.isEmptyString(addresses[i])) {
				mimeMessageHelper.addTo(addresses[i].trim());
			}
		}
	}
}
 
Example 5
Source File: NotificationEmailSender.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected void prepareMessage(MimeMessage mimeMessage, Notification notification, Staff recipient, StringBuilder text, Date now) throws Exception {
	if (!Settings.getBoolean(SettingCodes.EMAIL_NOTIFICATIONS_ENABLED, Bundle.SETTINGS, DefaultSettings.EMAIL_NOTIFICATIONS_ENABLED)) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.EMAIL_NOTIFICATIONS_DISABLED);
	}
	MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false, getEncoding());
	String subject = notification.getSubject();
	if (!CommonUtil.isEmptyString(subject)) {
		mimeMessageHelper.setSubject(subject);
	} else {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.EMAIL_EMPTY_SUBJECT);
	}
	String message = notification.getMessage();
	if (!CommonUtil.isEmptyString(message)) {
		mimeMessageHelper.setText(message, isHtml());
		text.append(message);
	} else {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.EMAIL_EMPTY_MESSAGE);
	}
	mimeMessageHelper.setFrom(Settings.getEmailNotificationFromAddress(), Settings.getEmailNotificationFromName());
	StaffOutVO recipientVO = staffDao.toStaffOutVO(recipient);
	Iterator<StaffContactDetailValue> contactsIt = recipient.getContactDetailValues().iterator();
	while (contactsIt.hasNext()) {
		StaffContactDetailValue contact = contactsIt.next();
		ContactDetailType contactType;
		if (!contact.isNa() && contact.isNotify() && (contactType = contact.getType()).isEmail()) {
			mimeMessageHelper.addTo(contact.getValue(),
					MessageFormat.format(EMAIL_TO_PERSONAL_NAME, recipientVO.getName(), L10nUtil.getContactDetailTypeName(Locales.NOTIFICATION, contactType.getNameL10nKey())));
		}
	}
}
 
Example 6
Source File: AbstractTest.java    From smtp-connection-pool with Apache License 2.0 5 votes vote down vote up
protected void send() throws Exception {
  try (ClosableSmtpConnection connection = smtpConnectionPool.borrowObject()) {
    MimeMessage mimeMessage = new MimeMessage(connection.getSession());
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false);
    mimeMessageHelper.addTo("[email protected]");
    mimeMessageHelper.setFrom("[email protected]");
    mimeMessageHelper.setSubject("foo");
    mimeMessageHelper.setText("example", false);
    connection.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
  }
}
 
Example 7
Source File: TestSendException.java    From smtp-connection-pool with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvalidateOnException() throws Exception {
  GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
  genericObjectPoolConfig.setMaxTotal(getMaxTotalConnection());
  genericObjectPoolConfig.setTestOnBorrow(true);

  // We need to instantiate a new factory and pool to set the flag on the factory
  transportFactory = SmtpConnectionFactoryBuilder.newSmtpBuilder().port(PORT).invalidateConnectionOnException(true).build();
  smtpConnectionPool = new SmtpConnectionPool(transportFactory, genericObjectPoolConfig);

  try (ClosableSmtpConnection connection = smtpConnectionPool.borrowObject()) {
    MimeMessage mimeMessage = new MimeMessage(connection.getSession());
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, false);
    mimeMessageHelper.addTo("[email protected]");
    mimeMessageHelper.setFrom("[email protected]");
    mimeMessageHelper.setSubject("foo");
    mimeMessageHelper.setText("example", false);
    // We stop the server before we actually send the message
    stopServer();
    connection.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
    Assert.fail("The connection should fail since the server is stopped");
  } catch (MailSendException | MessagingException e) {
    // It should come here, but the connection should not be returned in the pool
  }
  Assert.assertEquals(1, smtpConnectionPool.getBorrowedCount());
  Assert.assertEquals(1, smtpConnectionPool.getDestroyedCount());
  Assert.assertEquals(0, smtpConnectionPool.getReturnedCount());
}
 
Example 8
Source File: SimpleEmailServiceJavaMailSenderTest.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
private MimeMessage createMimeMessage() throws MessagingException {
	MimeMessage message = new MimeMessage(Session.getInstance(new Properties()));
	MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message);
	mimeMessageHelper.addTo("[email protected]");
	mimeMessageHelper.setText("body text");
	mimeMessageHelper.setSubject("subject");
	mimeMessageHelper.getMimeMessage().saveChanges();
	return message;
}
 
Example 9
Source File: ImapMessageTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testEncodedFromToAddresses() throws Exception
{
    // RFC1342
    String addressString = "[email protected]";
    String personalString = "�?р�?ений Ковальчук";
    InternetAddress address = new InternetAddress(addressString, personalString, "UTF-8");
    
    // Following method returns the address with quoted personal aka <["�?р�?ений Ковальчук"] <[email protected]>>
    // NOTE! This should be coincided with RFC822MetadataExtracter. Would 'addresses' be quoted or not? 
    // String decodedAddress = address.toUnicodeString();
    // Starting from javax.mail 1.5.6 the address is folded at linear whitespace so that each line is no longer than 76 characters, if possible.
    String decodedAddress = MimeUtility.decodeText(MimeUtility.fold(6, address.toString()));
    
    // InternetAddress.toString(new Address[] {address}) - is used in the RFC822MetadataExtracter
    // So, compare with that
    assertFalse("Non ASCII characters in the address should be encoded", decodedAddress.equals(InternetAddress.toString(new Address[] {address})));
    
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    
    MimeMessageHelper messageHelper = new MimeMessageHelper(message, false, "UTF-8");
    
    messageHelper.setText("This is a sample message for ALF-5647");
    messageHelper.setSubject("This is a sample message for ALF-5647");
    messageHelper.setFrom(address);
    messageHelper.addTo(address);
    messageHelper.addCc(address);
    
    // Creating the message node in the repository
    String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate();
    FileInfo messageFile = fileFolderService.create(testImapFolderNodeRef, name, ContentModel.TYPE_CONTENT);
    // Writing a content.
    new IncomingImapMessage(messageFile, serviceRegistry, message);
    
    // Getting the transformed properties from the repository
    // cm:originator, cm:addressee, cm:addressees, imap:messageFrom, imap:messageTo, imap:messageCc
    Map<QName, Serializable> properties = nodeService.getProperties(messageFile.getNodeRef());
    
    String cmOriginator = (String) properties.get(ContentModel.PROP_ORIGINATOR);
    String cmAddressee = (String) properties.get(ContentModel.PROP_ADDRESSEE);
    @SuppressWarnings("unchecked")
    List<String> cmAddressees = (List<String>) properties.get(ContentModel.PROP_ADDRESSEES);
    String imapMessageFrom = (String) properties.get(ImapModel.PROP_MESSAGE_FROM);
    String imapMessageTo = (String) properties.get(ImapModel.PROP_MESSAGE_TO);
    String imapMessageCc = (String) properties.get(ImapModel.PROP_MESSAGE_CC);
    
    assertNotNull(cmOriginator);
    assertEquals(decodedAddress, cmOriginator);
    assertNotNull(cmAddressee);
    assertEquals(decodedAddress, cmAddressee);
    assertNotNull(cmAddressees);
    assertEquals(1, cmAddressees.size());
    assertEquals(decodedAddress, cmAddressees.get(0));
    assertNotNull(imapMessageFrom);
    assertEquals(decodedAddress, imapMessageFrom);
    assertNotNull(imapMessageTo);
    assertEquals(decodedAddress, imapMessageTo);
    assertNotNull(imapMessageCc);
    assertEquals(decodedAddress, imapMessageCc);
}