org.junit.Rule#javax.mail.internet.MimeMessage源码实例Demo

下面列出了org.junit.Rule#javax.mail.internet.MimeMessage 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: james-project   文件: JamesMailetContextTest.java
@Test
public void sendMailForMessageAndEnvelopeShouldEnqueueEmailWithRootState() throws Exception {
    MimeMessage message = MimeMessageBuilder.mimeMessageBuilder()
        .addFrom(mailAddress.asString())
        .addToRecipient(mailAddress.asString())
        .setText("Simple text")
        .build();

    MailAddress sender = mailAddress;
    ImmutableList<MailAddress> recipients = ImmutableList.of(mailAddress);
    testee.sendMail(sender, recipients, message);

    ArgumentCaptor<Mail> mailArgumentCaptor = ArgumentCaptor.forClass(Mail.class);
    verify(spoolMailQueue).enQueue(mailArgumentCaptor.capture());
    verifyNoMoreInteractions(spoolMailQueue);

    assertThat(mailArgumentCaptor.getValue().getState()).isEqualTo(Mail.DEFAULT);
}
 
源代码2 项目: james-project   文件: ContentReplacerTest.java
@Test
public void applyPatternShouldModifyWhenMatchingSubject() throws Exception {
    ContentReplacer testee = new ContentReplacer(false);

    Mail mail = mock(Mail.class);
    MimeMessage mimeMessage = mock(MimeMessage.class);
    when(mail.getMessage())
        .thenReturn(mimeMessage);
    when(mimeMessage.getSubject())
        .thenReturn("test aa o");
    when(mimeMessage.getContentType())
        .thenReturn("text/plain");

    ImmutableList<ReplacingPattern> patterns = ImmutableList.of(new ReplacingPattern(Pattern.compile("test"), false, "TEST"),
        new ReplacingPattern(Pattern.compile("a"), true, "e"),
        new ReplacingPattern(Pattern.compile("o"), false, "o"));
    ReplaceConfig replaceConfig = ReplaceConfig.builder()
            .addAllSubjectReplacingUnits(patterns)
            .build();
    testee.replaceMailContentAndSubject(mail, replaceConfig, Optional.of(StandardCharsets.UTF_8));

    verify(mimeMessage).setSubject("TEST ee o", StandardCharsets.UTF_8.name());
}
 
源代码3 项目: commons-email   文件: EmailTest.java
@Test
public void testCorrectContentTypeForPNG() throws Exception
{
    email.setHostName(strTestMailServer);
    email.setSmtpPort(getMailServerPort());
    email.setFrom("[email protected]");
    email.addTo("[email protected]");
    email.setSubject("test mail");

    email.setCharset("ISO-8859-1");
    final File png = new File("./target/test-classes/images/logos/maven-feather.png");
    email.setContent(png, "image/png");
    email.buildMimeMessage();
    final MimeMessage msg = email.getMimeMessage();
    msg.saveChanges();
    assertEquals("image/png", msg.getContentType());
}
 
源代码4 项目: scipio-erp   文件: MimeMessageWrapper.java
public synchronized void setMessage(MimeMessage message) {
    if (message != null) {
        // serialize the message
        this.message = message;
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            message.writeTo(baos);
            baos.flush();
            serializedBytes = baos.toByteArray();
            this.contentType = message.getContentType();

            // see if this is a multi-part message
            Object content = message.getContent();
            if (content instanceof Multipart) {
                Multipart mp = (Multipart) content;
                this.parts = mp.getCount();
            } else {
                this.parts = 0;
            }
        } catch (IOException | MessagingException e) {
            Debug.logError(e, module);
        }
    }
}
 
源代码5 项目: cola-cloud   文件: MailSender.java
/**
 * 发送html邮件
 */
public void sendHtmlMail(MailSenderParams params) {
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        //helper.setFrom(new InternetAddress(this.getFrom(), MimeUtility.encodeText(this.name,"UTF-8", "B")));
        helper.setFrom(this.getFrom());
        helper.setTo(params.getMailTo());
        helper.setSubject(params.getTitle());
        helper.setText(params.getContent(), true);
        this.addAttachment(helper,params);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("发送邮件异常! from: " + name+ "! to: " + params.getMailTo());
    }
    javaMailSender.send(message);
}
 
源代码6 项目: olat   文件: MailHelper.java
/**
    * Create a configures mail message object that is ready to use
    * 
    * @return MimeMessage
    */
static MimeMessage createMessage() {
       Properties p = new Properties();
       p.put("mail.smtp.host", mailhost);
       p.put("mail.smtp.timeout", mailhostTimeout);
       p.put("mail.smtp.connectiontimeout", mailhostTimeout);
       p.put("mail.smtp.ssl.enable", sslEnabled);
       p.put("mail.smtp.ssl.checkserveridentity", sslCheckCertificate);
       Session mailSession;
       if (smtpAuth == null) {
           mailSession = javax.mail.Session.getInstance(p);
       } else {
           // use smtp authentication from configuration
           p.put("mail.smtp.auth", "true");
           mailSession = Session.getDefaultInstance(p, smtpAuth);
       }
       if (log.isDebugEnabled()) {
           // enable mail session debugging on console
           mailSession.setDebug(true);
       }
       return new MimeMessage(mailSession);
   }
 
@Test
public void testSendMultipartHtmlEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
    verify(javaMailSender).send(messageCaptor.capture());
    MimeMessage message = 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");
}
 
源代码8 项目: jakduk-api   文件: EmailService.java
public void sendBulk(EmailPayload emailPayload) throws MessagingException {

		// Prepare the evaluation context
		final Context ctx = new Context(emailPayload.getLocale());
		ctx.setVariables(emailPayload.getBody());

		// Prepare message using a Spring helper
		final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
		final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");

		message.setSubject(emailPayload.getSubject());
		message.setTo(emailPayload.getRecipientEmail());

		// Create the HTML body using Thymeleaf
		final String htmlContent = this.htmlTemplateEngine.process(emailPayload.getTemplateName(), ctx);
		message.setText(htmlContent, true /* isHtml */);

		// Send email
		this.mailSender.send(mimeMessage);
	}
 
源代码9 项目: james-project   文件: ContactExtractorTest.java
@Test
public void serviceShouldParseMultipleRecipients() throws Exception {
    String rawMessage = "From: [email protected]\r\n"
        + "To: User 1 <[email protected]>, =?UTF-8?Q?recip_>>_Fr=c3=a9d=c3=a9ric_RECIPIENT?= <[email protected]>\r\n"
        + "Subject: extract this recipient please\r\n"
        + "\r\n"
        + "Please!";
    MimeMessage message = MimeMessageUtil.mimeMessageFromString(rawMessage);
    FakeMail mail = FakeMail.builder()
        .name("mail")
        .mimeMessage(message)
        .sender(SENDER)
        .recipient("[email protected]")
        .build();
    mailet.init(mailetConfig);

    String expectedMessage = "{\"userEmail\" : \"" + SENDER + "\", \"emails\" : [ \"User 1 <[email protected]>\", \"\\\"recip >> Frédéric RECIPIENT\\\" <[email protected]>\" ]}";
    mailet.service(mail);

    assertThat(mail.getAttribute(ATTRIBUTE_NAME)).hasValueSatisfying(json ->
            assertThatJson(json.getValue().value().toString()).isEqualTo(expectedMessage));
}
 
源代码10 项目: appengine-tck   文件: MailHandlerServlet.java
/**
 * Stores subject and headers into memcache for test to confirm mail delivery.
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    try {
        MimeMessage message = new MimeMessage(session, req.getInputStream());
        MimeProperties mp = new MimeProperties(message);

        List<String> headers = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        Enumeration e = message.getAllHeaderLines();
        while (e.hasMoreElements()) {
            String headerLine = (String) e.nextElement();
            headers.add(headerLine);
            sb.append("\n").append(headerLine);
        }
        log.info("HEADERS: " + sb.toString());

        mp.headers = headers.toString();
        TestBase.putTempData(mp);
    } catch (MessagingException me) {
        throw new IOException("Error while processing email.", me);
    }
}
 
源代码11 项目: ehcache3-samples   文件: MailService.java
@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, StandardCharsets.UTF_8.name());
        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());
        }
    }
}
 
源代码12 项目: teammates   文件: JavamailService.java
/**
 * {@inheritDoc}
 */
@Override
public MimeMessage parseToEmail(EmailWrapper wrapper) throws MessagingException, IOException {
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage email = new MimeMessage(session);
    if (wrapper.getSenderName() == null || wrapper.getSenderName().isEmpty()) {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail()));
    } else {
        email.setFrom(new InternetAddress(wrapper.getSenderEmail(), wrapper.getSenderName()));
    }
    email.setReplyTo(new Address[] { new InternetAddress(wrapper.getReplyTo()) });
    email.addRecipient(Message.RecipientType.TO, new InternetAddress(wrapper.getRecipient()));
    if (wrapper.getBcc() != null && !wrapper.getBcc().isEmpty()) {
        email.addRecipient(Message.RecipientType.BCC, new InternetAddress(wrapper.getBcc()));
    }
    email.setSubject(wrapper.getSubject());
    email.setContent(wrapper.getContent(), "text/html");
    return email;
}
 
@Test
public void verifyEmailClickLinkRequiredActionsCleared() throws IOException, MessagingException {
    try (Closeable u = new UserAttributeUpdater(testRealm().users().get(testUserId))
            .setEmailVerified(true)
            .setRequiredActions()
            .update()) {
        testRealm().users().get(testUserId).executeActionsEmail(Arrays.asList(RequiredAction.VERIFY_EMAIL.name()));

        Assert.assertEquals(1, greenMail.getReceivedMessages().length);
        MimeMessage message = greenMail.getLastReceivedMessage();

        String verificationUrl = getPasswordResetEmailLink(message);

        driver.manage().deleteAllCookies();

        driver.navigate().to(verificationUrl);

        accountPage.setAuthRealm(testRealm().toRepresentation().getRealm());
        accountPage.navigateTo();

        loginPage.assertCurrent();
        loginPage.login("[email protected]", "password");

        accountPage.assertCurrent();
    }
}
 
@Test
public void javaMailSenderWithParseExceptionOnMimeMessagePreparator() {
	MockJavaMailSender sender = new MockJavaMailSender();
	MimeMessagePreparator preparator = new MimeMessagePreparator() {
		@Override
		public void prepare(MimeMessage mimeMessage) throws MessagingException {
			mimeMessage.setFrom(new InternetAddress(""));
		}
	};
	try {
		sender.send(preparator);
	}
	catch (MailParseException ex) {
		// expected
		assertTrue(ex.getCause() instanceof AddressException);
	}
}
 
源代码15 项目: james-project   文件: JamesMailetContext.java
/**
 * Place a mail on the spool for processing
 *
 * @param message the message to send
 * @throws MessagingException if an exception is caught while placing the mail on the spool
 */
@Override
public void sendMail(MimeMessage message) throws MessagingException {
    MailAddress sender = new MailAddress((InternetAddress) message.getFrom()[0]);
    Collection<MailAddress> recipients = new HashSet<>();
    Address[] addresses = message.getAllRecipients();
    if (addresses != null) {
        for (Address address : addresses) {
            // Javamail treats the "newsgroups:" header field as a
            // recipient, so we want to filter those out.
            if (address instanceof InternetAddress) {
                recipients.add(new MailAddress((InternetAddress) address));
            }
        }
    }
    sendMail(sender, recipients, message);
}
 
@Test
public void isMdnSentAutomaticallyShouldManageItsMimeType() throws Exception {
    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                            "Disposition: MDN-sent-automatically",
                            "text/plain")
                    ));
    scriptPart.setHeader("Content-Type", "text/plain");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    
    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isFalse();
}
 
源代码17 项目: jbpm-work-items   文件: SendMailWorkitemHandler.java
public Message sendMessage(Gmail service,
                           String to,
                           String from,
                           String subject,
                           String bodyText,
                           Document attachment)
        throws MessagingException, IOException {
    MimeMessage mimeMessage = createEmailWithAttachment(to,
                                                        from,
                                                        subject,
                                                        bodyText,
                                                        attachment);
    Message message = service.users().messages().send(from,
                                                      createMessageWithEmail(mimeMessage)).execute();

    return message;
}
 
源代码18 项目: disconf   文件: MailBean.java
/**
 * 发送html邮件
 *
 * @throws MessagingException
 * @throws AddressException
 */
public void sendHtmlMail(String from, String[] to, String title, String text)
        throws AddressException, MessagingException {

    long start = System.currentTimeMillis();

    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "GBK");

    InternetAddress[] toArray = new InternetAddress[to.length];
    for (int i = 0; i < to.length; i++) {
        toArray[i] = new InternetAddress(to[i]);
    }

    messageHelper.setFrom(new InternetAddress(from));
    messageHelper.setTo(toArray);
    messageHelper.setSubject(title);
    messageHelper.setText(text, true);
    mimeMessage = messageHelper.getMimeMessage();
    mailSender.send(mimeMessage);
    long end = System.currentTimeMillis();
    LOG.info("send mail start:" + start + " end :" + end);
}
 
源代码19 项目: jhipster-online   文件: MailServiceIT.java
@Test
public void testSendMultipartHtmlEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
    verify(javaMailSender).send(messageCaptor.capture());
    MimeMessage message = 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("JHipster Online <[email protected]>");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
源代码20 项目: Moss   文件: MailNotifierTest.java
@Test
public void should_send_mail_using_default_template() throws IOException, MessagingException {
    Map<String, Object> details = new HashMap<>();
    details.put("Simple Value", 1234);
    details.put("Complex Value", singletonMap("Nested Simple Value", "99!"));

    StepVerifier.create(notifier.notify(
        new InstanceStatusChangedEvent(instance.getId(), instance.getVersion(), StatusInfo.ofDown(details))))
                .verifyComplete();

    ArgumentCaptor<MimeMessage> mailCaptor = ArgumentCaptor.forClass(MimeMessage.class);
    verify(sender).send(mailCaptor.capture());

    MimeMessage mail = mailCaptor.getValue();

    assertThat(mail.getSubject()).isEqualTo("application-name (cafebabe) is DOWN");
    assertThat(mail.getRecipients(Message.RecipientType.TO)).containsExactly(new InternetAddress("[email protected]"));
    assertThat(mail.getRecipients(Message.RecipientType.CC)).containsExactly(new InternetAddress("[email protected]"));
    assertThat(mail.getFrom()).containsExactly(new InternetAddress("SBA <[email protected]>"));
    assertThat(mail.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");

    String body = extractBody(mail.getDataHandler());
    assertThat(body).isEqualTo(loadExpectedBody("expected-default-mail"));
}
 
源代码21 项目: Project   文件: SpitterMailServiceImpl.java
/**
* <p>描述:富文本email</p>
* @param to
* @param spittle
* @throws MessagingException
 */
public void sendRichEmail(String to, Spittle spittle) throws MessagingException {
	MimeMessage message = mailSender.createMimeMessage();
	MimeMessageHelper helper = new MimeMessageHelper(message, true);
	String spitterName = spittle.getSpitter().getFullName();
	helper.setFrom("[email protected]");
	helper.setTo(to);
	helper.setSubject("New spittle from " + spitterName);
	helper.setText("<html><body><img src='cid:spitterLogo'>"
			+ "<h4>"+spitterName+" says:</h4>"
			+ "<i>"+spittle.getText()+"</i>"
			+ "</body></html>", true);
	ClassPathResource couponImage = new ClassPathResource("/collateral/coupon.jpg");
	helper.addInline("spitterLogo", couponImage);
	mailSender.send(message);
}
 
源代码22 项目: pentaho-kettle   文件: MailTest.java
private Message createMimeMessage( String specialCharacters, File attachedFile ) throws Exception {
  Session session = Session.getInstance( new Properties() );
  Message message = new MimeMessage( session );

  MimeMultipart multipart = new MimeMultipart();
  MimeBodyPart attachedFileAndContent = new MimeBodyPart();
  attachedFile.deleteOnExit();
  // create a data source
  URLDataSource fds = new URLDataSource( attachedFile.toURI().toURL() );
  // get a data Handler to manipulate this file type;
  attachedFileAndContent.setDataHandler( new DataHandler( fds ) );
  // include the file in the data source
  String tempFileName = attachedFile.getName();
  message.setSubject( specialCharacters );
  attachedFileAndContent.setFileName( tempFileName );
  attachedFileAndContent.setText( specialCharacters );

  multipart.addBodyPart( attachedFileAndContent );
  message.setContent( multipart );

  return message;
}
 
源代码23 项目: spring-boot-demo   文件: MailServiceImpl.java
/**
 * 发送带附件的邮件
 *
 * @param to       收件人地址
 * @param subject  邮件主题
 * @param content  邮件内容
 * @param filePath 附件地址
 * @param cc       抄送地址
 * @throws MessagingException 邮件发送异常
 */
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
    MimeMessage message = mailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(from);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(content, true);
    if (ArrayUtil.isNotEmpty(cc)) {
        helper.setCc(cc);
    }
    FileSystemResource file = new FileSystemResource(new File(filePath));
    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    helper.addAttachment(fileName, file);

    mailSender.send(message);
}
 
源代码24 项目: scipio-erp   文件: JavaMailContainer.java
protected void processMessage(Message message, Session session) {
    if (message instanceof MimeMessage) {
        MimeMessageWrapper wrapper = new MimeMessageWrapper(session, (MimeMessage) message);
        try {
            ServiceMcaUtil.evalRules(dispatcher, wrapper, userLogin);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Problem processing message", module);
        }
    }
}
 
源代码25 项目: SpringBootLearn   文件: MailTest.java
/**
 * 发送静态邮箱
 * @throws Exception
 */
@Test
public void sendStaticMail() throws Exception {
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();

    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom(username);
    helper.setTo("[email protected]");
    helper.setSubject("测试主题:嵌入静态资源");
    helper.setText("<html><body><img src=\"cid:weixin_qrcode\" ></body></html>", true);
    FileSystemResource file = new FileSystemResource(new File("weixin_qrcode.jpg"));
    // addInline函数中资源名称jpg需要与正文中cid:weixin_qrcode对应起来
    helper.addInline("weixin_qrcode", file);
    javaMailSender.send(mimeMessage);

}
 
源代码26 项目: cuba   文件: EmailerTest.java
private MimeBodyPart getInlineAttachment(MimeMessage msg) throws IOException, MessagingException {
    assertTrue(msg.getContent() instanceof MimeMultipart);
    MimeMultipart mimeMultipart = (MimeMultipart) msg.getContent();

    Object content2 = mimeMultipart.getBodyPart(0).getContent();
    assertTrue(content2 instanceof MimeMultipart);
    MimeMultipart textBodyPart = (MimeMultipart) content2;

    return (MimeBodyPart) textBodyPart.getBodyPart(1);
}
 
源代码27 项目: activiti6-boot2   文件: EmailServiceTaskTest.java
@Deployment
public void testSendEmail() throws Exception {
  
  String from = "[email protected]";
  boolean male = true;
  String recipientName = "John Doe";
  String recipient = "[email protected]";
  Date now = new Date();
  String orderId = "123456";
  
  Map<String, Object> vars = new HashMap<String, Object>();
  vars.put("sender", from);
  vars.put("recipient", recipient);
  vars.put("recipientName", recipientName);
  vars.put("male", male);
  vars.put("now", now);
  vars.put("orderId", orderId);
  
  runtimeService.startProcessInstanceByKey("sendMailExample", vars);
  
  List<WiserMessage> messages = wiser.getMessages();
  assertEquals(1, messages.size());
  
  WiserMessage message = messages.get(0);
  MimeMessage mimeMessage = message.getMimeMessage();
  
  assertEquals("Your order " + orderId + " has been shipped", mimeMessage.getHeader("Subject", null));
  assertEquals(from, mimeMessage.getHeader("From", null));
  assertTrue(mimeMessage.getHeader("To", null).contains(recipient));
}
 
源代码28 项目: matrix-appservice-email   文件: EmailEndPoint.java
@Override
protected void sendEventImpl(_SubscriptionEvent ev) {
    try {
        Optional<MimeMessage> msg = formatter.get(ev);
        if (!msg.isPresent()) {
            log.info("Formatter did not return message, ignoring notification");
            return;
        }

        send(msg.get());
        log.info("Email bridge: sending event {} to {} - success", ev.getType(), getIdentity());
    } catch (IOException | MessagingException e) {
        log.error("Could not send notification to {} about event {}", getIdentity(), ev.getType(), e);
    }
}
 
源代码29 项目: FlexibleLogin   文件: ForgotPasswordCommand.java
private MimeMessage buildMessage(User player, String email, String newPassword, MailConfig emailConfig,
                                 Session session) throws MessagingException, UnsupportedEncodingException {
    String serverName = Sponge.getServer().getBoundAddress()
            .map(sa -> sa.getAddress().getHostAddress())
            .orElse("Minecraft Server");
    ImmutableMap<String, String> variables = ImmutableMap.of("player", player.getName(),
            "server", serverName,
            "password", newPassword);

    MimeMessage message = new MimeMessage(session);
    String senderEmail = emailConfig.getAccount();

    //sender email with an alias
    message.setFrom(new InternetAddress(senderEmail, emailConfig.getSenderName()));
    message.setRecipient(RecipientType.TO, new InternetAddress(email, player.getName()));
    message.setSubject(emailConfig.getSubject(serverName, player.getName()).toPlain());

    //current time
    message.setSentDate(Calendar.getInstance().getTime());
    String textContent = emailConfig.getText(serverName, player.getName(), newPassword).toPlain();

    //html part
    BodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(textContent, "text/html; charset=UTF-8");

    //plain text
    BodyPart textPart = new MimeBodyPart();
    textPart.setContent(textContent.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " "), "text/plain; charset=UTF-8");

    Multipart alternative = new MimeMultipart("alternative");
    alternative.addBodyPart(htmlPart);
    alternative.addBodyPart(textPart);
    message.setContent(alternative);
    return message;
}
 
源代码30 项目: quarkus   文件: MailerImplTest.java
@Test
void testAttachmentAsStreamLegacy() throws MessagingException, IOException {
    String payload = UUID.randomUUID().toString();
    byte[] bytes = payload.getBytes(StandardCharsets.UTF_8);
    Iterable<Byte> iterable = () -> new Iterator<Byte>() {
        private int index = 0;

        @Override
        public boolean hasNext() {
            return bytes.length > index;
        }

        @Override
        public Byte next() {
            return bytes[index++];
        }
    };

    legacyMailer.send(Mail.withText(TO, "Test", "testAttachmentAsStream")
            .addAttachment("my-file.txt", Flowable.fromIterable(iterable), TEXT_CONTENT_TYPE))
            .toCompletableFuture().join();
    assertThat(wiser.getMessages()).hasSize(1);
    WiserMessage actual = wiser.getMessages().get(0);
    assertThat(getContent(actual)).contains("testAttachment");
    MimeMessage msg = actual.getMimeMessage();
    assertThat(msg.getSubject()).isEqualTo("Test");
    assertThat(msg.getFrom()[0].toString()).isEqualTo(FROM);
    String value = getAttachment("my-file.txt", (MimeMultipart) actual.getMimeMessage().getContent());
    assertThat(value).isEqualTo(payload);
}