Java Code Examples for org.springframework.mail.javamail.JavaMailSenderImpl#createMimeMessage()
The following examples show how to use
org.springframework.mail.javamail.JavaMailSenderImpl#createMimeMessage() .
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: EmailSender.java From open-cloud with MIT License | 5 votes |
/** * 发送邮件 */ public void sendSimpleMail(JavaMailSenderImpl javaMailSender, EmailMessage emailMessage) throws Exception { MimeMessage message = null; message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(emailMessage.getTo()); if (emailMessage.getCc() != null && emailMessage.getCc().length > 0) { helper.setCc(emailMessage.getCc()); } helper.setFrom(javaMailSender.getUsername()); helper.setSubject(emailMessage.getSubject()); helper.setText(emailMessage.getContent(), true); this.addAttachment(helper, emailMessage); javaMailSender.send(message); }
Example 2
Source File: MailSender.java From cola-cloud with MIT License | 5 votes |
public static void main(String[] args) { JavaMailSenderImpl js=new JavaMailSenderImpl(); js.setHost("smtp.qq.com"); js.setUsername("[email protected]"); js.setPassword("mygdzwlcjlxpbghc"); Properties props = new Properties(); props.put("mail.smtp.auth", true); props.put("mail.smtp.ssl.enable", true); props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.timeout", 25000); js.setJavaMailProperties(props); MimeMessage message = null; try { message = js.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); // helper.setFrom(new InternetAddress(this.getFrom(), MimeUtility.encodeText(this.name,"UTF-8", "B"))); helper.setFrom("[email protected]"); helper.setTo("[email protected]"); helper.setSubject("测试"); helper.setText("测试内容"); //addAttachmentStatic(helper,params); } catch (Exception e) { e.printStackTrace(); } js.send(message); }
Example 3
Source File: EmailServiceImpl.java From DimpleBlog with Apache License 2.0 | 5 votes |
@Override public void sendHtmlMail(String to, String title, String content) { EmailSetting emailSetting = configService.selectConfigByConfigKey(ConfigKey.CONFIG_KEY_EMAIL_SETTING, EmailSetting.class); JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setUsername(emailSetting.getUser()); mailSender.setHost(emailSetting.getHost()); mailSender.setDefaultEncoding("utf-8"); mailSender.setPassword(emailSetting.getPassword()); mailSender.setPort(emailSetting.getPort()); Properties properties = new Properties(); properties.put("mail.smtp.host", emailSetting.getHost()); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.socketFactory.fallback", "false"); // 只处理SSL的连接,对于非SSL的连接不做处理 properties.put("mail.smtp.port", emailSetting.getPort()); properties.put("mail.smtp.socketFactory.port", emailSetting.getPort()); properties.put("mail.smtp.ssl.enable", true); Session session = Session.getInstance(properties); MimeMessage mimeMessage = mailSender.createMimeMessage(); try { MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true); mimeMessageHelper.setFrom(emailSetting.getFromEmail()); mimeMessageHelper.setTo(to); if (StringUtils.isNotEmpty(emailSetting.getStationmasterEmail())) { mimeMessageHelper.setBcc(emailSetting.getStationmasterEmail()); } mimeMessageHelper.setSubject(title); mimeMessageHelper.setText(content, true); mailSender.setSession(session); mailSender.send(mimeMessage); } catch (MessagingException e) { log.error(e.getMessage(), e); } }
Example 4
Source File: ReportJob.java From boubei-tss with Apache License 2.0 | 5 votes |
private void send(String _ms, String[] receiver, ReceiverReports rr) { String title = EasyUtils.list2Str(rr.reportTitles); JavaMailSenderImpl sender = MailUtil.getMailSender(_ms); MimeMessage mailMessage = sender.createMimeMessage(); try { // 设置utf-8或GBK编码,否则邮件会有乱码 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8"); messageHelper.setFrom( MailUtil.getEmailFrom(_ms) ); // 发送者 messageHelper.setTo(receiver); // 接受者 messageHelper.setSubject(EX.TIMER_REPORT + title); // 主题 // 邮件内容,注意加参数true StringBuffer html = new StringBuffer(); html.append("<html>"); html.append("<head>"); html.append("<style type='text/css'> " ); html.append(" table { border-collapse:collapse; border-spacing:0; }"); html.append(" td { line-height: 1.42857143; vertical-align: top; border: 1px solid black; text-align: left;}"); html.append(" td { margin:0; padding:0; padding: 2px 2px 2px 2px; font-family: 微软雅黑; font-size: 15px;}"); html.append(" thead td { background-color:#E4E6F5; font-weight: bold; }"); html.append("</style>"); html.append("</head>"); html.append("<body>"); for(int index = 0; index < rr.reportIds.size(); index++) { buildEmailContent(rr, index, messageHelper, html); } html.append("</body>"); html.append("</html>"); log.debug(html); messageHelper.setText(html.toString(), true); sender.send(mailMessage); } catch (Exception e) { log.error(" error when send report email ", e); } }
Example 5
Source File: MailUtil.java From boubei-tss with Apache License 2.0 | 5 votes |
public static void sendHTML(String subject, String htmlText, String receiver[], String _ms, File...attaches) { // 邮件内容,注意加参数true StringBuffer html = new StringBuffer(); html.append("<html>"); html.append("<head>"); html.append("<style type='text/css'> " ); html.append(" body { margin:0; padding:5px; font-family: 微软雅黑; font-size: 15px;}"); html.append("</style>"); html.append("</head>"); html.append("<body>"); html.append(htmlText); html.append("</body>"); html.append("</html>"); JavaMailSenderImpl sender = MailUtil.getMailSender(_ms); MimeMessage mailMsg = sender.createMimeMessage(); try { // 设置utf-8或GBK编码,否则邮件会有乱码 MimeMessageHelper mh = new MimeMessageHelper(mailMsg, true, "utf-8"); mh.setFrom( getEmailFrom(_ms) ); // 发送者 mh.setTo( preCheatEmails(receiver) ); // 接受者 mh.setSubject(subject); // 主题 mh.setText( html.toString(), true ); for(File attach : attaches) { mh.addAttachment(MimeUtility.encodeWord(attach.getName()), attach); } sender.send(mailMsg); } catch (Exception e) { log.error("发送邮件【" +subject+ "】出错了, " + Arrays.asList(receiver) + ", " + e.getMessage()); } }
Example 6
Source File: EmailServiceImpl.java From BlogSystem with Apache License 2.0 | 5 votes |
@Override public boolean sendFeedback(int bloggerId, String subject, String content, String contact) { JavaMailSenderImpl mailSender = mailManager.getMailSender( websiteProperties.getMailSenderAddress(), websiteProperties.getMailSenderPassword()); MimeMessage mailMessage = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true, "utf-8"); // 设置发件人 helper.setFrom(websiteProperties.getMailSenderAddress()); // 设置收件人 helper.setTo(websiteProperties.getManageEmailAddress()); // 设置主题 helper.setSubject(subject); // 邮件体 BloggerAccount account = bloggerId > 0 ? accountDao.getAccountById(bloggerId) : null; helper.setText(account != null ? "from:\n\tusername: " + account.getUsername() + "\n\tid: " + account.getId() + "\n\n" + content + "\n\n\tcontact: " + contact : content + "\n\n\tcontact: " + contact); mailSender.send(mailMessage);// 发送邮件 } catch (Exception e) { e.printStackTrace(); return false; } return true; }
Example 7
Source File: DefaultMailService.java From iotplatform with Apache License 2.0 | 5 votes |
private void sendMail(JavaMailSenderImpl mailSender, String mailFrom, String email, String subject, String message) throws IoTPException { try { MimeMessage mimeMsg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(mimeMsg, "UTF-8"); helper.setFrom(mailFrom); helper.setTo(email); helper.setSubject(subject); helper.setText(message, true); mailSender.send(helper.getMimeMessage()); } catch (Exception e) { throw handleException(e); } }
Example 8
Source File: MailComposerImplTest.java From yes-cart with Apache License 2.0 | 5 votes |
@Test public void testComposeMimeMessageInternalTextAndHtmlVersion() throws MessagingException, IOException, ClassNotFoundException { final CacheManager cacheManager = mockery.mock(CacheManager.class); final Cache cache = mockery.mock(Cache.class); mockery.checking(new Expectations() {{ allowing(cacheManager).getCache("contentService-templateSupport"); will(returnValue(cache)); }}); final TemplateProcessor templates = new MailComposerTemplateSupportGroovyImpl(new GroovyGStringTemplateSupportImpl(cacheManager)); // of course you would use DI in any real-world cases JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("localhost"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); String textTemplate = "Bender lives in theme park with blackjack poetess"; String htmlTemplate = "<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>"; Map<String, byte[]> attachments = Collections.emptyMap(); MailComposerImpl mailComposer = new MailComposerImpl(null, templates); mailComposer.composeMessage(helper, textTemplate, htmlTemplate, attachments, Collections.EMPTY_LIST, "SHOP10", "en", "test"); assertTrue(helper.isMultipart()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.getMimeMessage().writeTo(byteArrayOutputStream); String str = byteArrayOutputStream.toString("UTF-8"); assertNotNull(str); // html and text present in mail message assertTrue(str.contains("Bender lives in theme park with blackjack poetess")); assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>")); mockery.assertIsSatisfied(); }
Example 9
Source File: MailComposerImplTest.java From yes-cart with Apache License 2.0 | 5 votes |
@Test public void testComposeMimeMessageInternalTextAndHtmlVersionWithAttach() throws MessagingException, IOException, ClassNotFoundException { final CacheManager cacheManager = mockery.mock(CacheManager.class); final Cache cache = mockery.mock(Cache.class); mockery.checking(new Expectations() {{ allowing(cacheManager).getCache("contentService-templateSupport"); will(returnValue(cache)); }}); final TemplateProcessor templates = new MailComposerTemplateSupportGroovyImpl(new GroovyGStringTemplateSupportImpl(cacheManager)); // of course you would use DI in any real-world cases JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("localhost"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); String textTemplate = "Bender lives in theme park with blackjack poetess"; String htmlTemplate = "<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>"; Map<String, byte[]> attachments = Collections.singletonMap("attachment:image/jpeg;myimage.jpg", new byte[]{1, 1, 1}); MailComposerImpl mailComposer = new MailComposerImpl(null, templates); mailComposer.composeMessage(helper, textTemplate, htmlTemplate, attachments, Collections.EMPTY_LIST, "SHOP10", "en", "test"); assertTrue(helper.isMultipart()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.getMimeMessage().writeTo(byteArrayOutputStream); String str = byteArrayOutputStream.toString("UTF-8"); assertNotNull(str); // html and text present in mail message assertTrue(str.contains("Bender lives in theme park with blackjack poetess")); assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>")); // attachment assertTrue(str.contains("Content-Type: image/jpeg; name=myimage.jpg")); assertTrue(str.contains("Content-Transfer-Encoding: base64")); assertTrue(str.contains("Content-Disposition: attachment; filename=myimage.jpg")); assertTrue(str.contains("AQEB")); mockery.assertIsSatisfied(); }
Example 10
Source File: MailComposerImplTest.java From yes-cart with Apache License 2.0 | 5 votes |
/** * Text template only */ @Test public void testComposeMimeMessageInternalTextVersionOnly() throws MessagingException, IOException, ClassNotFoundException { final CacheManager cacheManager = mockery.mock(CacheManager.class); final Cache cache = mockery.mock(Cache.class); mockery.checking(new Expectations() {{ allowing(cacheManager).getCache("contentService-templateSupport"); will(returnValue(cache)); }}); final TemplateProcessor templates = new MailComposerTemplateSupportGroovyImpl(new GroovyGStringTemplateSupportImpl(cacheManager)); // of course you would use DI in any real-world cases JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("localhost"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); String textTemplate = "Bender lives in theme park with blackjack poetess"; String htmlTemplate = null; Map<String, byte[]> attachments = Collections.emptyMap(); MailComposerImpl mailComposer = new MailComposerImpl(null, templates); mailComposer.composeMessage(helper, textTemplate, htmlTemplate, attachments, Collections.EMPTY_LIST, "SHOP10", "en", "test"); assertTrue(helper.isMultipart()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.getMimeMessage().writeTo(byteArrayOutputStream); String str = byteArrayOutputStream.toString("UTF-8"); assertNotNull(str); // html and text present in mail message assertTrue(str.contains("Bender lives in theme park with blackjack poetess")); mockery.assertIsSatisfied(); }
Example 11
Source File: MailComposerImplTest.java From yes-cart with Apache License 2.0 | 5 votes |
/** * html only */ @Test public void testComposeMimeMessageInternalHtmlVersionOnly() throws MessagingException, IOException, ClassNotFoundException { final CacheManager cacheManager = mockery.mock(CacheManager.class); final Cache cache = mockery.mock(Cache.class); mockery.checking(new Expectations() {{ allowing(cacheManager).getCache("contentService-templateSupport"); will(returnValue(cache)); }}); final TemplateProcessor templates = new MailComposerTemplateSupportGroovyImpl(new GroovyGStringTemplateSupportImpl(cacheManager)); // of course you would use DI in any real-world cases JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("localhost"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); String textTemplate = null; String htmlTemplate = "<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>"; Map<String, byte[]> attachments = Collections.emptyMap(); MailComposerImpl mailComposer = new MailComposerImpl(null, templates); mailComposer.composeMessage(helper, textTemplate, htmlTemplate, attachments, Collections.EMPTY_LIST, "SHOP10", "en", "test"); assertTrue(helper.isMultipart()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.getMimeMessage().writeTo(byteArrayOutputStream); String str = byteArrayOutputStream.toString("UTF-8"); assertNotNull(str); // html and text present in mail message assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>")); mockery.assertIsSatisfied(); }
Example 12
Source File: NeteaseMailUtil.java From charging_pile_cloud with MIT License | 4 votes |
/** * @param to 目的邮箱 * @param title 标题 * @param text 内容 * @return */ private static boolean sendMailText(String to, String title, String text) { JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); SimpleMailMessage mailMessage = new SimpleMailMessage(); Properties prop = new Properties(); System.out.println("sendMail...util..."); try { //设定mail server senderImpl.setHost(emailHost); //senderImpl.setPort(587); // 设置收件人,寄件人 用数组发送多个邮件 // String[] array = new String[] {"[email protected]","[email protected]"}; // mailMessage.setTo(array); mailMessage.setTo(to); mailMessage.setFrom(sendEmail); mailMessage.setSubject(title); mailMessage.setText(text); senderImpl.setUsername(emailUsername); senderImpl.setPassword(authorizationPwd); prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); prop.setProperty("mail.smtp.socketFactory.fallback", "false"); prop.setProperty("mail.smtp.port", "465"); prop.setProperty("mail.smtp.socketFactory.port", "465"); // 设置传输协议 prop.setProperty("mail.transport.protocol", "smtp"); prop.put("mail.smtp.auth", isAuth); prop.put("mail.smtp.timeout", linkTimeout); senderImpl.setJavaMailProperties(prop); System.out.println("发送信息:" + text); MimeMessage msg = senderImpl.createMimeMessage(); msg.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(sendEmail)); //发送邮件 senderImpl.send(mailMessage); System.out.println("发送邮件成功"); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("发送邮件失败"); return false; } }
Example 13
Source File: NeteaseMailUtil.java From charging_pile_cloud with MIT License | 4 votes |
/** * 发送网页图片邮箱 * * @param to * @param title * @param text * @return */ private static boolean sendMailHtml(String to, String title, String text) { JavaMailSenderImpl senderImpl = new JavaMailSenderImpl(); //SimpleMailMessage mailMessage = new SimpleMailMessage(); //建立邮件消息,发送简单邮件和html邮件的区别 MimeMessage mailMessage = senderImpl.createMimeMessage(); Properties prop = new Properties(); System.out.println("sendMail...util..."); try { //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用, //multipart模式 MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8"); prop.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); prop.setProperty("mail.smtp.socketFactory.fallback", "false"); prop.setProperty("mail.smtp.port", "465"); prop.setProperty("mail.smtp.socketFactory.port", "465"); // 设置传输协议 prop.setProperty("mail.transport.protocol", "smtp"); prop.put("mail.smtp.auth", isAuth); prop.put("mail.smtp.timeout", linkTimeout); senderImpl.setJavaMailProperties(prop); senderImpl.setUsername(emailUsername); senderImpl.setPassword(authorizationPwd); //设定mail server senderImpl.setHost(emailHost); //senderImpl.setPort(587); // 设置收件人,寄件人 用数组发送多个邮件 // String[] array = new String[] {"[email protected]","[email protected]"}; // mailMessage.setTo(array); messageHelper.setTo(to); messageHelper.setFrom(sendEmail); messageHelper.setSubject(title); messageHelper.setText(messageHtml(text), true); System.out.println("发送信息:" + text); MimeMessage msg = senderImpl.createMimeMessage(); msg.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(sendEmail)); //发送邮件 senderImpl.send(mailMessage); System.out.println("发送邮件成功"); return true; } catch (Exception e) { e.printStackTrace(); System.out.println("发送邮件失败"); return false; } }
Example 14
Source File: MailComposerImplTest.java From yes-cart with Apache License 2.0 | 4 votes |
@Test public void testComposeMimeMessageInternalFullIntegration() throws MessagingException, IOException, ClassNotFoundException { final CacheManager cacheManager = mockery.mock(CacheManager.class); final Cache cache = mockery.mock(Cache.class); mockery.checking(new Expectations() {{ allowing(cacheManager).getCache("contentService-templateSupport"); will(returnValue(cache)); allowing(cache).get(with(any(String.class))); will(returnValue(null)); allowing(cache).put(with(any(String.class)), with(any(Object.class))); }}); final TemplateProcessor templates = new MailComposerTemplateSupportGroovyImpl(new GroovyGStringTemplateSupportImpl(cacheManager)); final MailTemplateResourcesProvider mailTemplateResourcesProvider = mockery.mock(MailTemplateResourcesProvider.class); mockery.checking(new Expectations() {{ oneOf(mailTemplateResourcesProvider).getTemplate(Collections.singletonList("default/mail/"), "SHOP10", "en", "imtest", ".txt"); will(returnValue(IOUtils.toString(new FileInputStream(new File("src/test/resources/mailtemplates/default/imtest/imtest.txt")), "UTF-8"))); oneOf(mailTemplateResourcesProvider).getTemplate(Collections.singletonList("default/mail/"), "SHOP10", "en", "imtest", ".html"); will(returnValue(IOUtils.toString(new FileInputStream(new File("src/test/resources/mailtemplates/default/imtest/imtest.html")), "UTF-8"))); oneOf(mailTemplateResourcesProvider).getTemplate(Collections.singletonList("default/mail/"), "SHOP10", "en", "imtest", ".properties"); will(returnValue(IOUtils.toString(new FileInputStream(new File("src/test/resources/mailtemplates/default/imtest/imtest.properties")), "UTF-8"))); oneOf(mailTemplateResourcesProvider).getResource(Collections.singletonList("default/mail/"), "SHOP10", "en", "imtest", "test.gif"); will(returnValue(IOUtils.toByteArray(new FileInputStream(new File("src/test/resources/mailtemplates/default/imtest/resources/test.gif"))))); oneOf(mailTemplateResourcesProvider).getResource(Collections.singletonList("default/mail/"), "SHOP10", "en", "imtest", "test.jpeg"); will(returnValue(IOUtils.toByteArray(new FileInputStream(new File("src/test/resources/mailtemplates/default/imtest/resources/test.jpeg"))))); }}); // of course you would use DI in any real-world cases JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("localhost"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); MailComposerImpl mailComposer = new MailComposerImpl(mailTemplateResourcesProvider, templates); mailComposer.composeMessage( message, "SHOP10", "en", Collections.singletonList("default/mail/"), "imtest", "[email protected]", "[email protected]", "[email protected]", "[email protected]", createModel()); assertTrue(helper.isMultipart()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.getMimeMessage().writeTo(byteArrayOutputStream); String str = byteArrayOutputStream.toString("UTF-8"); assertNotNull(str); // html and text present in mail message assertTrue(str.contains("Bender lives in theme park with blackjack poetess")); assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>")); assertTrue(str.contains("From: [email protected]")); assertTrue(str.contains("To: [email protected]")); assertTrue(str.contains("[email protected]")); assertTrue(str.contains("Bcc: [email protected]")); assertEquals("Тема письма", message.getSubject()); mockery.assertIsSatisfied(); }
Example 15
Source File: MailComposerImplTest.java From yes-cart with Apache License 2.0 | 4 votes |
/** * html only */ @Test public void testConvertMailEntityToMimeMessage() throws MessagingException, IOException, ClassNotFoundException { final CacheManager cacheManager = mockery.mock(CacheManager.class); final Cache cache = mockery.mock(Cache.class); mockery.checking(new Expectations() {{ allowing(cacheManager).getCache("contentService-templateSupport"); will(returnValue(cache)); allowing(cache).get("<% \n %>${name} is awesome!"); will(returnValue(null)); allowing(cache).put(with(equal("<% \n %>${name} is awesome!")), with(any(Object.class))); }}); final TemplateProcessor templates = new MailComposerTemplateSupportGroovyImpl(new GroovyGStringTemplateSupportImpl(cacheManager)); // of course you would use DI in any real-world cases final Mail mail = new MailEntity(); mail.setShopCode("SHOP10"); mail.setSubject("Тема письма"); mail.setFrom("[email protected]"); mail.setRecipients("[email protected]"); mail.setCc("[email protected]"); mail.setBcc("[email protected]"); mail.setTextVersion("Bender lives in theme park with blackjack poetess"); mail.setHtmlVersion("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>"); JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("localhost"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); MailComposerImpl mailComposer = new MailComposerImpl(null, templates); mailComposer.convertMessage(mail, message); assertTrue(helper.isMultipart()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.getMimeMessage().writeTo(byteArrayOutputStream); String str = byteArrayOutputStream.toString("UTF-8"); assertNotNull(str); // html and text present in mail message assertTrue(str.contains("Bender lives in theme park with blackjack poetess")); assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>")); assertTrue(str.contains("From: [email protected]")); assertTrue(str.contains("To: [email protected]")); assertTrue(str.contains("[email protected]")); assertTrue(str.contains("Bcc: [email protected]")); assertEquals("Тема письма", message.getSubject()); mockery.assertIsSatisfied(); }
Example 16
Source File: MailComposerImplTest.java From yes-cart with Apache License 2.0 | 4 votes |
/** * html only */ @Test public void testConvertMailEntityToMimeMessageWithAttach() throws MessagingException, IOException, ClassNotFoundException { final CacheManager cacheManager = mockery.mock(CacheManager.class); final Cache cache = mockery.mock(Cache.class); mockery.checking(new Expectations() {{ allowing(cacheManager).getCache("contentService-templateSupport"); will(returnValue(cache)); allowing(cache).get("<% \n %>${name} is awesome!"); will(returnValue(null)); allowing(cache).put(with(equal("<% \n %>${name} is awesome!")), with(any(Object.class))); }}); final TemplateProcessor templates = new MailComposerTemplateSupportGroovyImpl(new GroovyGStringTemplateSupportImpl(cacheManager)); // of course you would use DI in any real-world cases final Mail mail = new MailEntity(); mail.setShopCode("SHOP10"); mail.setSubject("Тема письма"); mail.setFrom("[email protected]"); mail.setRecipients("[email protected]"); mail.setCc("[email protected]"); mail.setBcc("[email protected]"); mail.setTextVersion("Bender lives in theme park with blackjack poetess"); mail.setHtmlVersion("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>"); final MailPart attach = mail.addPart(); attach.setFilename("myimage.jpg"); attach.setResourceId("attachment:image/jpeg;myimage.jpg"); attach.setData(new byte[] { 1, 1, 1 }); JavaMailSenderImpl sender = new JavaMailSenderImpl(); sender.setHost("localhost"); MimeMessage message = sender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8"); MailComposerImpl mailComposer = new MailComposerImpl(null, templates); mailComposer.convertMessage(mail, message); assertTrue(helper.isMultipart()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); helper.getMimeMessage().writeTo(byteArrayOutputStream); String str = byteArrayOutputStream.toString("UTF-8"); assertNotNull(str); // html and text present in mail message assertTrue(str.contains("Bender lives in theme park with blackjack poetess")); assertTrue(str.contains("<h2>Bender</h2> lives in theme park with:<br> blackjack<br>poetess<br>")); assertTrue(str.contains("From: [email protected]")); assertTrue(str.contains("To: [email protected]")); assertTrue(str.contains("[email protected]")); assertTrue(str.contains("Bcc: [email protected]")); assertEquals("Тема письма", message.getSubject()); // attachment assertTrue(str.contains("Content-Type: image/jpeg; name=myimage.jpg")); assertTrue(str.contains("Content-Transfer-Encoding: base64")); assertTrue(str.contains("Content-Disposition: attachment; filename=myimage.jpg")); assertTrue(str.contains("AQEB")); mockery.assertIsSatisfied(); }