Java Code Examples for javax.mail.internet.MimeMessage

The following are top voted examples for showing how to use javax.mail.internet.MimeMessage. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: web-framework-for-java   File: MailHelper.java   Source Code and License 11 votes vote down vote up
public static void sendMail(String host, int port, String username, String password, String recipients,
		String subject, String content, String from) throws AddressException, MessagingException {
	
	Properties props = new Properties();
	props.put("mail.smtp.auth", "true");
	props.put("mail.smtp.starttls.enable", "true");
	props.put("mail.smtp.host", host);
	props.put("mail.smtp.port", port);

	Session session = Session.getInstance(props, new javax.mail.Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(username, password);
		}
	});

	Message message = new MimeMessage(session);
	message.setFrom(new InternetAddress(from));
	message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
	message.setSubject(subject);
	message.setText(content);

	Transport.send(message);
}
 
Example 2
Project: sushi-bar-BE   File: EmailSenderImpl.java   Source Code and License 8 votes vote down vote up
@Override
public void sendEmail(final UserDTO user, String url) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
            message.setTo(user.getEmail());
            message.setSubject(SUBJECT);
            message.setFrom(EMAIL_FROM); // could be parameterized...
            Map model = new HashMap();
            model.put("user", user);
            model.put("url", url);
            String text = VelocityEngineUtils.mergeTemplateIntoString(
                    velocityEngine, "org/enricogiurin/sushibar/registration-confirmation.vm", model);
            message.setText(text, true);
        }
    };
    this.emailSender.send(preparator);
}
 
Example 3
Project: HustEating   File: Mail.java   Source Code and License 7 votes vote down vote up
/**
 * 发送邮件,从公邮里发邮件给成员变量email。
 *
 * @throws Exception 可能会有异常抛出,建议打出Log。
 */
public void sendCodeMail() throws MessagingException, UnsupportedEncodingException {
    if (email == null) {
        Log.e("sendCodeMail","调用错误");
        return;
    }
    //创建一封邮件
    MimeMessage message = createCodeMessage(session, myEmailAccount, email);

    Transport transport = session.getTransport();

    //使用 邮箱账号 和 密码 连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致, 否则报错
    transport.connect(myEmailAccount, myEmailPassword);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}
 
Example 4
Project: openpaas-mailets   File: ClassificationRequestBodySerializerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void toJsonAsStringShouldReturnTextBodyWhenMultipartAndTextHtml() throws Exception {
    MimeMessage message = MimeMessageBuilder.mimeMessageBuilder()
        .setMultipartWithBodyParts(
            MimeMessageBuilder.bodyPartBuilder()
                .data("<p>this is my body</p>")
                .type("text/html")
                .build())
        .addHeader("Date", "Wed, 24 May 2017 06:23:11 -0700")
        .build();

    FakeMail mail = FakeMail.from(message);
    
    ClassificationRequestBodySerializer testee = new ClassificationRequestBodySerializer(mail, new FakeUUIDGenerator());
    String jsonAsString = testee.toJsonAsString();

    assertThatJson(jsonAsString)
        .isEqualTo("{\"messageId\":\"524e4f85-2d2f-4927-ab98-bd7a2f689773\"," +
            "\"from\":[]," +
            "\"recipients\":{\"to\":[],\"cc\":[],\"bcc\":[]}," +
            "\"subject\":[\"\"]," +
            "\"date\":\"2017-05-24T13:23:11Z\"," +
            "\"textBody\":\"this is my body\\n\\n\"}");
}
 
Example 5
Project: jhipster-microservices-example   File: MailServiceIntTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testSendMultipartHtmlEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject","testContent", true, true);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart)((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example 6
Project: k-framework   File: JavaMailMessage.java   Source Code and License 6 votes vote down vote up
public void sendMailBatch(List<String> to, String title, String content) throws MessagingException {
    Session session = Session.getDefaultInstance(properties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(fromAddress));
    to.forEach(address -> {
        try {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(address));
        } catch (MessagingException ignored) {
        }
    });
    message.setSubject(title);
    message.setContent(content, "text/html;charset=UTF-8");
    Transport.send(message);
}
 
Example 7
Project: REST-Web-Services   File: MailServiceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Async
@Override
public void sendMailWithNewPassword(
        @NotBlank @Email final String email,
        @NotBlank final String newPassword
) {
    log.info("Called with e-mail {}, newPassword {}", email, newPassword);

    try {
        final JavaMailSenderImpl sender = new JavaMailSenderImpl();

        final MimeMessage message = sender.createMimeMessage();

        final MimeMessageHelper helper = new MimeMessageHelper(message);

        helper.setTo(email);
        helper.setSubject("Recover password");
        helper.setText("Your new password: " + "<b>" + newPassword + "</b>", true);

        sendMail(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
 
Example 8
Project: Spring-cloud-gather   File: EmailServiceImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldSendRemindEmail() throws MessagingException, IOException {

	final String subject = "subject";
	final String text = "text";

	Recipient recipient = new Recipient();
	recipient.setAccountName("test");
	recipient.setEmail("[email protected]");

	when(env.getProperty(NotificationType.REMIND.getSubject())).thenReturn(subject);
	when(env.getProperty(NotificationType.REMIND.getText())).thenReturn(text);

	emailService.send(NotificationType.REMIND, recipient, null);

	verify(mailSender).send(captor.capture());

	MimeMessage message = captor.getValue();
	assertEquals(subject, message.getSubject());
	// TODO check other fields
}
 
Example 9
Project: exam   File: StudentExamControllerTest.java   Source Code and License 6 votes vote down vote up
@Test
@RunAsStudent
public void testAbortPrivateExam() throws Exception {
    Exam studentExam = createPrivateStudentExam();
    Result result = request(Helpers.PUT, String.format("/app/student/exam/abort/%s", studentExam.getHash()), null);
    assertThat(result.status()).isEqualTo(200);

    // Check that correct mail was sent
    assertThat(greenMail.waitForIncomingEmail(MAIL_TIMEOUT, 1)).isTrue();
    MimeMessage[] mails = greenMail.getReceivedMessages();
    assertThat(mails).hasSize(1);
    assertThat(mails[0].getFrom()[0].toString()).contains(ConfigFactory.load().getString("sitnet.email.system.account"));
    assertThat(mails[0].getSubject()).isEqualTo("Personal exam has been abandoned");
    String body = GreenMailUtil.getBody(mails[0]);
    // Make sure there is no link to review
    assertThat(body).doesNotContain("<a href");
}
 
Example 10
Project: weibo   File: Mail.java   Source Code and License 6 votes vote down vote up
/**
 * 创建一封只包含文本的简单邮件
 *
 * @param session
 *            和服务器交互的会话
 * @param sendMail
 *            发件人邮箱
 * @param receiveMail
 *            收件人邮箱
 * @return
 * @throws Exception
 */
public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail, String username,String pwd)
		throws Exception {
	// 1. 创建一封邮件
	MimeMessage message = new MimeMessage(session);

	// 2. From: 发件人(昵称有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改昵称)
	message.setFrom(new InternetAddress(sendMail, "Mircle", "UTF-8"));

	// 3. To: 收件人(可以增加多个收件人、抄送、密送)
	message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "", "UTF-8"));

	// 4. Subject: 邮件主题(标题有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改标题)
	message.setSubject(subject, "UTF-8");

	// 5. Content: 邮件正文(可以使用html标签)(内容有广告嫌疑,避免被邮件服务器误认为是滥发广告以至返回失败,请修改发送内容)
	message.setContent(getContent(username,pwd), "text/html;charset=UTF-8");

	// 6. 设置发件时间
	message.setSentDate(new Date());

	// 7. 保存设置
	message.saveChanges();

	return message;
}
 
Example 11
Project: Higher-Cloud-Computing-Project   File: EmailUtils.java   Source Code and License 6 votes vote down vote up
public static void sendAccountActivateEmail(String email, String uuid, int userId) {
  Session session;
  try {
    session = getSession();
    MimeMessage message = new MimeMessage(session);
    message.setSubject("������֤��");
    message.setSentDate(new Date());
    message.setFrom(new InternetAddress(FROM));
    message.setRecipient(RecipientType.TO, new InternetAddress(email));
    message.setContent("�����û�"+userId+":������֤��Ϊ��"+uuid,
        "text/html;charset=utf-8");
    message.saveChanges();
    Transport.send(message);
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 12
Project: omero-ms-queue   File: MessageBuilder.java   Source Code and License 6 votes vote down vote up
public MimeMessage buildMimeMessage(PlainTextMail data) {
    requireNonNull(data, "data");
    
    MimeMailMessage builder = mimeBuilder();
    builder.setFrom(config.fromAddress().get());
    builder.setTo(data.getRecipient().get());
    builder.setSubject(data.getSubject());
    builder.setText(data.getContent());
    
    return builder.getMimeMessage();
}
 
Example 13
Project: sztw   File: MailCore.java   Source Code and License 6 votes vote down vote up
/**
 *
 * @param session 和服务器交互的会话
 * @param mail 邮件内容
 * @return
 * @throws Exception
 */
private static MimeMessage createMimeMessage(Session session, String SendAccount, Mail mail) throws Exception {
    MimeMessage message = new MimeMessage(session);
    //From: 发件人
    message.setFrom(new InternetAddress(SendAccount, mail.getPersonal(), "UTF-8"));
    // To: 收件人
    message.setRecipients(MimeMessage.RecipientType.TO, mail.getAddresses());
    // Subject: 邮件主题
    message.setSubject(mail.getSubject(), "UTF-8");
    // Content: 邮件正文(可以使用html标签)
    message.setContent(mail.getContext(), "text/html;charset=UTF-8");
    // 设置发件时间
    message.setSentDate(new Date());
    message.saveChanges();
    return message;
}
 
Example 14
Project: Spring-cloud-gather   File: EmailServiceImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldSendBackupEmail() throws MessagingException, IOException {

	final String subject = "subject";
	final String text = "text";
	final String attachment = "attachment.json";

	Recipient recipient = new Recipient();
	recipient.setAccountName("test");
	recipient.setEmail("[email protected]");

	when(env.getProperty(NotificationType.BACKUP.getSubject())).thenReturn(subject);
	when(env.getProperty(NotificationType.BACKUP.getText())).thenReturn(text);
	when(env.getProperty(NotificationType.BACKUP.getAttachment())).thenReturn(attachment);

	emailService.send(NotificationType.BACKUP, recipient, "{\"name\":\"test\"");

	verify(mailSender).send(captor.capture());

	MimeMessage message = captor.getValue();
	assertEquals(subject, message.getSubject());
	// TODO check other fields
}
 
Example 15
Project: iotplatform   File: MailPlugin.java   Source Code and License 6 votes vote down vote up
private void sendMail(SendMailActionMsg msg) throws MessagingException {
  log.debug("Sending mail {}", msg);
  MimeMessage mailMsg = mailSender.createMimeMessage();
  MimeMessageHelper helper = new MimeMessageHelper(mailMsg, "UTF-8");
  helper.setFrom(msg.getFrom());
  helper.setTo(msg.getTo());
  if (!StringUtils.isEmpty(msg.getCc())) {
    helper.setCc(msg.getCc());
  }
  if (!StringUtils.isEmpty(msg.getBcc())) {
    helper.setBcc(msg.getBcc());
  }
  helper.setSubject(msg.getSubject());
  helper.setText(msg.getBody());
  mailSender.send(helper.getMimeMessage());
  log.debug("Mail sent {}", msg);
}
 
Example 16
Project: patient-portal   File: MailService.java   Source Code and License 6 votes vote down vote up
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
    log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
        isMultipart, isHtml, to, subject, content);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(jHipsterProperties.getMail().getFrom());
        message.setSubject(subject);
        message.setText(content, isHtml);
        javaMailSender.send(mimeMessage);
        log.debug("Sent email to User '{}'", to);
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.warn("Email could not be sent to user '{}'", to, e);
        } else {
            log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
        }
    }
}
 
Example 17
Project: matrix-appservice-email   File: EmailEndPoint.java   Source Code and License 6 votes vote down vote up
@Override
protected void sendMessageImpl(_BridgeSubscription sub, _MatrixBridgeMessage msg) {
    log.info("Email bridge: sending message from {} to {} - start", msg.getSender(), getIdentity());

    try {
        Optional<MimeMessage> mimeMsg = formatter.get(sub, msg);
        if (!mimeMsg.isPresent()) {
            log.info("Email bridge: formatter did not return any content for matrix message, ignoring");
        } else {
            send(mimeMsg.get());
            log.info("Email bridge: sending message from {} to {} - success", msg.getSender(), getIdentity());
        }
    } catch (Exception e) {
        log.error("Email bridge: sending message from {} to {} - failure", msg.getSender(), getIdentity());
        throw new RuntimeException(e);
    }

    log.info("Email bridge: sending message from {} to {} - end", msg.getSender(), getIdentity());
}
 
Example 18
Project: tulingchat   File: MailUtil.java   Source Code and License 6 votes vote down vote up
/**
 * 发送html邮件
 */
@Async("mailAsync")
public void sendHtmlMail(String to, String subject, String content) {
	MimeMessage message = mailSender.createMimeMessage();
	try {
		//true表示需要创建一个multipart message
		MimeMessageHelper helper = new MimeMessageHelper(message, true);
		helper.setFrom(from);
		helper.setTo(to);
		helper.setSubject(subject);
		helper.setText(content, true);
		helper.setSentDate(new Date());
		mailSender.send(message);
		logger.info("html邮件发送成功");
	} catch (MessagingException e) {
		logger.error("发送html邮件时发生异常!", e);
	}
}
 
Example 19
Project: alfresco-repository   File: AbstractMailActionExecuterTest.java   Source Code and License 6 votes vote down vote up
protected MimeMessage sendMessage(String from, String subject, String template, final Action mailAction)
{
    if (from != null)
    {
        mailAction.setParameterValue(MailActionExecuter.PARAM_FROM, from);
    }
    mailAction.setParameterValue(MailActionExecuter.PARAM_SUBJECT, subject);
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE, template);
    mailAction.setParameterValue(MailActionExecuter.PARAM_TEMPLATE_MODEL, getModel());

    RetryingTransactionHelper txHelper = APP_CONTEXT_INIT.getApplicationContext().getBean("retryingTransactionHelper", RetryingTransactionHelper.class);

    return txHelper.doInTransaction(new RetryingTransactionCallback<MimeMessage>()
    {
        @Override
        public MimeMessage execute() throws Throwable
        {
            ACTION_SERVICE.executeAction(mailAction, null);

            return ACTION_EXECUTER.retrieveLastTestMessage();
        }
    }, true);
}
 
Example 20
Project: kettle_support_kettle8.0   File: Message.java   Source Code and License 5 votes vote down vote up
public static boolean createMimeMessage() {
	try {
		// 用props对象来创建并初始化session对象
		session = Session.getDefaultInstance(props, null);
		// 用session对象来创建并初始化邮件对象
		message = new MimeMessage(session);
		// 生成附件组件的实例
		mp = new MimeMultipart();
	} catch (Exception e) {
		return false;
	}
	return true;
}
 
Example 21
Project: ctsms   File: NewsletterEmailSender.java   Source Code and License 5 votes vote down vote up
@Override
protected int prepare(MimeMessage mimeMessage, Newsletter entity,
		Proband recipient) throws Exception {

       //http://www.javabeat.net/how-to-send-email-using-spring-framework/

	return 0;
}
 
Example 22
Project: alfresco-greenmail   File: GreenMailUtil.java   Source Code and License 5 votes vote down vote up
/**
 * Convenience method which creates a new {@link MimeMessage} from an input stream
 */
public static  MimeMessage newMimeMessage(InputStream inputStream)  {
    try {
        return new MimeMessage(Session.getDefaultInstance(new Properties()), inputStream);
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 23
Project: ats-framework   File: ImapFolder.java   Source Code and License 5 votes vote down vote up
/**
 * This method will convert a MIME message to meta data
 *
 * @param mimeMessage   the input MimeMessage instance
 * @return              the MetaData produced
 * @throws RbvStorageException
 */
protected ImapMetaData createImapMetaData(
                                           MimeMessage mimeMessage ) throws RbvException {

    try {
        MimePackage mimePackage = new MimePackage(mimeMessage);
        ImapMetaData metaData = new ImapMetaData(mimePackage);

        return metaData;

    } catch (PackageException pe) {
        throw new RbvStorageException("Could not get meta data from " + getDescription(), pe);
    }

}
 
Example 24
Project: spring-io   File: MailServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSendEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject","testContent", false, false);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getContent()).isInstanceOf(String.class);
    assertThat(message.getContent().toString()).isEqualTo("testContent");
    assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
 
Example 25
Project: qualitoast   File: MailServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSendActivationEmail() throws Exception {
    User user = new User();
    user.setLangKey(Constants.DEFAULT_LANGUAGE);
    user.setLogin("john");
    user.setEmail("[email protected]");
    mailService.sendActivationEmail(user);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
    assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getContent().toString()).isNotEmpty();
    assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example 26
Project: jhipster-microservices-example   File: MailServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSendHtmlEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject","testContent", false, true);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getContent()).isInstanceOf(String.class);
    assertThat(message.getContent().toString()).isEqualTo("testContent");
    assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example 27
Project: ats-framework   File: MimePackage.java   Source Code and License 5 votes vote down vote up
private MimePackage( String parentNestedPath,
                     int previousSiblings,
                     MimeMessage message,
                     Folder folder ) throws PackageException {

    setNestedPath(parentNestedPath, previousSiblings);
    this.message = message;
    this.partOfImapFolder = folder;

    decompose();
}
 
Example 28
Project: blog-examples   File: ClientRequestAPI.java   Source Code and License 5 votes vote down vote up
private static MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException {
	Properties props = new Properties();
	Session session = Session.getDefaultInstance(props, null);
	MimeMessage email = new MimeMessage(session);
	email.setFrom(new InternetAddress(from));
	email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
	email.setSubject(subject);
	email.setText(bodyText);
	return email;
}
 
Example 29
Project: spring-io   File: MailServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSendPasswordResetMail() throws Exception {
    User user = new User();
    user.setLangKey("en");
    user.setLogin("john");
    user.setEmail("[email protected]");
    mailService.sendPasswordResetMail(user);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
    assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getContent().toString()).isNotEmpty();
    assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example 30
Project: reactive-components   File: TestMail.java   Source Code and License 5 votes vote down vote up
private MimeMessage createMessage(Session session, String body) {
    try {
        MimeMessage mesage = new MimeMessage(session);
        mesage.setSubject("Test Mail");
        mesage.setText(body);
        return mesage;
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 31
Project: alfresco-greenmail   File: GreenMail.java   Source Code and License 5 votes vote down vote up
/**
 * @return Returns all messags in all folders for all users
 * {@link GreenMailUtil} has a bunch of static helper methods to extract body text etc.
 */
public MimeMessage[] getReceivedMessages() {
    List msgs = managers.getImapHostManager().getAllMessages();
    MimeMessage[] ret = new MimeMessage[msgs.size()];
    for (int i = 0; i < msgs.size(); i++) {
        SimpleStoredMessage simpleStoredMessage = (SimpleStoredMessage) msgs.get(i);
        ret[i] = simpleStoredMessage.getMimeMessage();
    }
    return ret;
}
 
Example 32
Project: timesheet-upload   File: EmailServiceImpl.java   Source Code and License 5 votes vote down vote up
private void sendSimpleMailWithAttachment(final String fromAddress, final List<String> toAddress, final List<String> ccAddress, final String subject, final String mailContent, final List<MultipartFile> attachFiles) {
    mailSender.send(new MimeMessagePreparator() {
        @Override
        public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            messageHelper.setFrom(fromAddress);
            messageHelper.setTo(toAddress.toArray(new String[toAddress.size()]));
            if (ccAddress != null && ccAddress.size() > 0) {
                messageHelper.setCc(ccAddress.toArray(new String[ccAddress.size()]));
            }
            messageHelper.setSubject(subject);
            messageHelper.setText(mailContent);

            for (final MultipartFile attachFile : attachFiles) {
                // determines if there is an upload file, attach it to the e-mail
                if (attachFile != null) {
                    String attachName = attachFile.getOriginalFilename();
                    messageHelper.addAttachment(attachName, new InputStreamSource() {
                        @Override
                        public InputStream getInputStream() throws IOException {
                            return attachFile.getInputStream();
                        }
                    });
                } else {
                    log.info("Attached file is Empty. Skipping the file " + attachFile + " in mail.");
                }
            }
        }
    });
}
 
Example 33
Project: BasicsProject   File: EmailUtil.java   Source Code and License 5 votes vote down vote up
/**
 * @Title: send
 * @Description: TODO(发送带附件的邮件)
 * @author [email protected] (苟志强)
 * @date  2017-6-6 下午4:29:56
 * @param to 接收用户账户
 * @param title 邮件标题
 * @param content 邮件内容
 * @param affix 附件路径
 * @param affixName 发送后显示名称
 * @return 是否发送成功
 */
public static boolean send(String to,String title,String content,String affix,String affixName) {
	Properties props = new Properties();
	//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
	props.put("mail.smtp.host", host);
	//需要经过授权,也就是有户名和密码的校验,这样才能通过验证
	props.put("mail.smtp.auth", "true");
	//用刚刚设置好的props对象构建一个session
	Session session = Session.getDefaultInstance(props);
	//有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使
	//用(你可以在控制台(console)上看到发送邮件的过程)
	session.setDebug(true);
	//用session为参数定义消息对象
	MimeMessage message = new MimeMessage(session);
	try{
		//加载发件人地址
		message.setFrom(new InternetAddress(from));
		//加载收件人地址
		message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
		//加载标题
		message.setSubject(title);
		// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
		Multipart multipart = new MimeMultipart();         

		//设置邮件的文本内容
		BodyPart contentPart = new MimeBodyPart();
		contentPart.setText(content);
		multipart.addBodyPart(contentPart);
		//添加附件
		if(affix!=null&&!"".equals(affix)&&affixName!=null&&!"".equals(affixName)){
			BodyPart messageBodyPart= new MimeBodyPart();
			DataSource source = new FileDataSource(affix);
			//添加附件的内容
			messageBodyPart.setDataHandler(new DataHandler(source));
			//添加附件的标题
			messageBodyPart.setFileName(MimeUtility.encodeText(affixName));
			multipart.addBodyPart(messageBodyPart);
		}
		//将multipart对象放到message中
		message.setContent(multipart);
		//保存邮件
		message.saveChanges();
		//   发送邮件
		Transport transport = session.getTransport("smtp");
		//连接服务器的邮箱
		transport.connect(host, user, pwd);
		//把邮件发送出去
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		return true;
	}catch(Exception e){
		e.printStackTrace();
		return false;
	}
}
 
Example 34
Project: REST-Web-Services   File: MailServiceImpl.java   Source Code and License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Async
@Override
public void sendMailWithActivationToken(
        @NotBlank @Email final String email,
        @NotBlank final String token
) {
    log.info("Called with e-mail {}, token {}", email, token);

    try {
        final JavaMailSenderImpl sender = new JavaMailSenderImpl();

        final MimeMessage message = sender.createMimeMessage();

        final MimeMessageHelper helper = new MimeMessageHelper(message);

        helper.setTo(email);
        helper.setSubject("Complete registration");
        helper.setText("To activation your account, click the link below:<br />"
                + "<a href='" + "https://localhost:8443" + "/register/thanks?token=" + token + "'>" +
                "Click here to complete your registration" +
                "</a>", true);

        sendMail(message);
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
 
Example 35
Project: c4sg-services   File: EmailServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSendVolunteerApplicantEmail() throws MessagingException {
	
	Organization org = new Organization();
	org.setName("Test Organization");
	org.setContactEmail("[email protected]");
	org.setContactName("John Sloan");
	org.setContactPhone("9898989899");
	
	User user = new User();
	user.setEmail("[email protected]");
	user.setFirstName("John");
	user.setLastName("Sloan");
	user.setChatUsername("jsloan");
	
	Project project = new Project();
	project.setId(110);
	project.setName("Test Project");
	
	Map<String, Object> mailContext = new HashMap<String, Object>();
   	mailContext.put("org", org);
   	mailContext.put("user", user);
   	mailContext.put("projectLink", "http://codeforsocialgood.org");
   	mailContext.put("project", project);
   	
   	mailService.sendWithContext(from, user.getEmail(), "", "Test Email", "applicant-application", mailContext);
   	
   	// received message
   	MimeMessage[] receivedMessages = mailer.getReceivedMessages();
       assertEquals(1, receivedMessages.length);
       
       MimeMessage msg = receivedMessages[0];
       
       assertThat(from, is(msg.getFrom()[0].toString()));
       assertThat("Test Email", is(msg.getSubject()));
}
 
Example 36
Project: cmc-claim-store   File: EmailServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSendEmailSuccess() throws MessagingException {
    EmailData emailData = SampleEmailData.getDefault();
    doNothing().when(javaMailSender).send(any(MimeMessage.class));
    emailService.sendEmail("[email protected]", emailData);
    verify(javaMailSender).send(mimeMessage);
}
 
Example 37
Project: spring-io   File: MailServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSendHtmlEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject","testContent", false, true);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getContent()).isInstanceOf(String.class);
    assertThat(message.getContent().toString()).isEqualTo("testContent");
    assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example 38
Project: TorgCRM-Server   File: MailServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCreationEmail() throws Exception {
    User user = new User();
    user.setLangKey(Constants.DEFAULT_LANGUAGE);
    user.setLogin("john");
    user.setEmail("[email protected]");
    mailService.sendCreationEmail(user);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
    assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getContent().toString()).isNotEmpty();
    assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example 39
Project: patient-portal   File: MailServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCreationEmail() throws Exception {
    User user = new User();
    user.setLangKey("en");
    user.setLogin("john");
    user.setEmail("[email protected]");
    mailService.sendCreationEmail(user);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
    assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getContent().toString()).isNotEmpty();
    assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example 40
Project: spring-io   File: MailServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSendActivationEmail() throws Exception {
    User user = new User();
    user.setLangKey("en");
    user.setLogin("john");
    user.setEmail("[email protected]");
    mailService.sendActivationEmail(user);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
    assertThat(message.getFrom()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getContent().toString()).isNotEmpty();
    assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}