javax.mail.internet.MimeMessage Java Examples
The following examples show how to use
javax.mail.internet.MimeMessage.
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: MailHelper.java From olat with Apache License 2.0 | 7 votes |
/** * 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); }
Example #2
Source File: MailServiceImpl.java From spring-boot-demo with MIT License | 6 votes |
/** * 发送带附件的邮件 * * @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); }
Example #3
Source File: MailSender.java From cola-cloud with MIT License | 6 votes |
/** * 发送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); }
Example #4
Source File: JavamailService.java From teammates with GNU General Public License v2.0 | 6 votes |
/** * {@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; }
Example #5
Source File: RequiredActionEmailVerificationTest.java From keycloak with Apache License 2.0 | 6 votes |
@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("test-user@localhost", "password"); accountPage.assertCurrent(); } }
Example #6
Source File: JavaMailSenderTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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); } }
Example #7
Source File: MimeMessageWrapper.java From scipio-erp with Apache License 2.0 | 6 votes |
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); } } }
Example #8
Source File: MailServiceIntTest.java From e-commerce-microservice with Apache License 2.0 | 6 votes |
@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("test@localhost"); assertThat(message.getContent()).isInstanceOf(Multipart.class); assertThat(aos.toString()).isEqualTo("\r\ntestContent"); assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); }
Example #9
Source File: EmailService.java From jakduk-api with MIT License | 6 votes |
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); }
Example #10
Source File: JamesMailetContext.java From james-project with Apache License 2.0 | 6 votes |
/** * 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); }
Example #11
Source File: AutomaticallySentMailDetectorImplTest.java From james-project with Apache License 2.0 | 6 votes |
@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(); }
Example #12
Source File: SendMailWorkitemHandler.java From jbpm-work-items with Apache License 2.0 | 6 votes |
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; }
Example #13
Source File: ContactExtractorTest.java From james-project with Apache License 2.0 | 6 votes |
@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)); }
Example #14
Source File: MailBean.java From disconf with Apache License 2.0 | 6 votes |
/** * 发送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); }
Example #15
Source File: MailServiceIT.java From jhipster-online with Apache License 2.0 | 6 votes |
@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 <test@localhost>"); assertThat(message.getContent()).isInstanceOf(Multipart.class); assertThat(aos.toString()).isEqualTo("\r\ntestContent"); assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8"); }
Example #16
Source File: EmailTest.java From commons-email with Apache License 2.0 | 6 votes |
@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()); }
Example #17
Source File: MailService.java From ehcache3-samples with Apache License 2.0 | 6 votes |
@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()); } } }
Example #18
Source File: MailHandlerServlet.java From appengine-tck with Apache License 2.0 | 6 votes |
/** * 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); } }
Example #19
Source File: MailNotifierTest.java From Moss with Apache License 2.0 | 6 votes |
@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")); }
Example #20
Source File: ContentReplacerTest.java From james-project with Apache License 2.0 | 6 votes |
@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()); }
Example #21
Source File: JamesMailetContextTest.java From james-project with Apache License 2.0 | 6 votes |
@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); }
Example #22
Source File: SpitterMailServiceImpl.java From Project with Apache License 2.0 | 6 votes |
/** * <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); }
Example #23
Source File: MailTest.java From pentaho-kettle with Apache License 2.0 | 6 votes |
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; }
Example #24
Source File: SimpleMailStoreTest.java From james-project with Apache License 2.0 | 5 votes |
@Test public void storeMailShouldUseLocalPartWhenSupportsVirtualHosting() throws Exception { MailAddress recipient = MailAddressFixture.OTHER_AT_JAMES; when(usersRepository.getUsername(recipient)).thenReturn(Username.of(recipient.getLocalPart())); FakeMail mail = FakeMail.builder() .name("name") .mimeMessage(mimeMessage) .build(); testee.storeMail(recipient, mail); verify(mailboxAppender).append(any(MimeMessage.class), eq(Username.of(recipient.getLocalPart())), eq(FOLDER)); }
Example #25
Source File: MailSender.java From SensorWebClient with GNU General Public License v2.0 | 5 votes |
public static void sendPasswordMail(String address, String newPassword) { LOGGER.debug("send new password to: " + address); final String text = SesConfig.mailTextPassword_en + ": " + "\n\n" + SesConfig.mailTextPassword_de + ": " + "\n\n" + newPassword; Session session = Session.getDefaultInstance(getProperties(), getMailAuthenticator()); try { // create a new message Message msg = new MimeMessage(session); // set sender and receiver msg.setFrom(new InternetAddress(SesConfig.SENDER_ADDRESS)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false)); // set subject to mail msg.setSubject(SesConfig.mailSubjectPassword_en + "/" + SesConfig.mailSubjectPassword_de); msg.setText(text); msg.setSentDate(new Date()); // send mail Transport.send(msg); LOGGER.debug("mail send succesfully done"); } catch (Exception e) { LOGGER.error("Error occured while sending password mail: " + e.getMessage(), e); } }
Example #26
Source File: MailServiceIntTest.java From TeamDojo with Apache License 2.0 | 5 votes |
@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("test@localhost"); assertThat(message.getContent()).isInstanceOf(String.class); assertThat(message.getContent().toString()).isEqualTo("testContent"); assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8"); }
Example #27
Source File: CmmnMailTaskTest.java From flowable-engine with Apache License 2.0 | 5 votes |
protected String getMessage(MimeMessage mimeMessage) { try { DataHandler dataHandler = mimeMessage.getDataHandler(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); dataHandler.writeTo(baos); baos.flush(); return baos.toString(); } catch (Exception e) { throw new RuntimeException("Couldn't get message", e); } }
Example #28
Source File: TestServlet.java From javamail with Apache License 2.0 | 5 votes |
/** * Sand example email */ @Override protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse response) throws ServletException, IOException { String toEmail = httpServletRequest.getParameter("to"); String body = httpServletRequest.getParameter("body"); if (toEmail == null || toEmail.length() == 0) { throw new ServletException("No \"to\" parameter!"); } if (body == null || body.length() == 0) { body = "No body!"; } try { Date now = new Date(); String from = mailSession.getProperty("mail.from"); if (from == null || from.length() == 0) { from = "[email protected]"; } MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); InternetAddress[] address = { new InternetAddress(toEmail) }; message.setRecipients(Message.RecipientType.TO, address); message.setSubject("JavaMail test at " + now); message.setSentDate(now); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText("Body's text (text)\n\n" + body, "UTF-8"); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent("<p>Body's text <strong>(html)</strong></p><p>" + body.replace("\n", "<br/>")+"</p>", "text/html; charset=UTF-8"); Multipart multiPart = new MimeMultipart("alternative"); multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); message.setContent(multiPart); mailSession.getTransport().sendMessage(message, address); httpServletRequest.setAttribute("sent", Boolean.TRUE); } catch (Exception ex) { httpServletRequest.setAttribute("sent", Boolean.FALSE); throw new ServletException("Error sending example e-mail!", ex); } doGet(httpServletRequest, response); }
Example #29
Source File: MailTest.java From SpringBootLearn with Apache License 2.0 | 5 votes |
/** * 发送静态邮箱 * @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); }
Example #30
Source File: ManageSieveMailetTestCase.java From james-project with Apache License 2.0 | 5 votes |
@Test public final void testRenameScriptsExtraArgs() throws Exception { sieveRepository.putScript(USERNAME, OLD_SCRIPT_NAME, SCRIPT_CONTENT); MimeMessage message = prepareMimeMessage("RENAMESCRIPT \"" + OLD_SCRIPT_NAME + "\" \"" + NEW_SCRIPT_NAME + "\" extra"); Mail mail = createUnauthenticatedMail(message); mailet.service(mail); ensureResponse("Re: RENAMESCRIPT \"" + OLD_SCRIPT_NAME + "\" \"" + NEW_SCRIPT_NAME + "\" extra", "NO \"Too many arguments: extra\""); }