List of usage examples for javax.mail.internet MimeMessage setText
@Override public void setText(String text, String charset, String subtype) throws MessagingException
From source file:ru.codemine.ccms.mail.EmailService.java
public void sendSimpleMessage(String address, String subject, String content) { try {/*from w ww.j a v a2 s . c o m*/ Properties props = new Properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "true"); props.put("mail.mime.charset", "UTF-8"); props.put("mail.smtp.ssl.enable", ssl); Session session = Session.getInstance(props, new EmailAuthenticator(username, password)); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(username, "")); message.setRecipient(Message.RecipientType.TO, new InternetAddress(address)); message.setSubject(subject); message.setText(content, "utf-8", "html"); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); } catch (MessagingException | UnsupportedEncodingException ex) { log.error( "? ? email, : " + ex.getLocalizedMessage()); ex.printStackTrace(); } }
From source file:com.mgmtp.perfload.perfalyzer.reporting.email.EmailReporter.java
private void sendMessage(final String subject, final String content) { try {//from ww w. j a va2s . c om Session session = (authenticator != null) ? Session.getInstance(smtpProps, authenticator) : Session.getInstance(smtpProps); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress)); msg.setSubject(subject); msg.addRecipients(Message.RecipientType.TO, on(',').join(toAddresses)); msg.setText(content, UTF_8.name(), "html"); Transport.send(msg); } catch (MessagingException e) { log.error("Error while creating report e-mail", e); } }
From source file:org.awknet.commons.mail.Mail.java
public void send() throws AddressException, MessagingException, FileNotFoundException, IOException { int count = recipientsTo.size() + recipientsCc.size() + recipientsBcc.size(); if (count == 0) return;//from www . j ava 2s .c o m deleteDuplicates(); Properties javaMailProperties = new Properties(); if (fileName.equals("") || fileName == null) fileName = DEFAULT_PROPERTIES_FILE; javaMailProperties.load(getClass().getResourceAsStream(fileName)); final String mailUsername = javaMailProperties.getProperty("mail.autentication.username"); final String mailPassword = javaMailProperties.getProperty("mail.autentication.password"); final String mailFrom = javaMailProperties.getProperty("mail.autentication.mail_from"); Session session = Session.getInstance(javaMailProperties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mailUsername, mailPassword); } }); final MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(mailFrom)); msg.setRecipients(Message.RecipientType.TO, getToRecipientsArray()); msg.setRecipients(Message.RecipientType.CC, getCcRecipientsArray()); msg.setRecipients(Message.RecipientType.BCC, getBccRecipientsArray()); msg.setSentDate(new Date()); msg.setSubject(mailSubject); msg.setText(mailText, "UTF-8", "html"); // msg.setText(mailText); //OLD WAY new Thread(new Runnable() { public void run() { try { Transport.send(msg); Logger.getLogger(Mail.class.getName()).log(Level.INFO, "email was sent successfully!"); } catch (MessagingException ex) { Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, "Cant send email!", ex); } } }).start(); }
From source file:com.silverpeas.mailinglist.service.job.TestMessageChecker.java
@Test public void testProcessEmailHtmlText() throws MessagingException, IOException { MessageListener mockListener1 = mock(MessageListener.class); when(mockListener1.getComponentId()).thenReturn("componentId"); when(mockListener1.checkSender("bart.simpson@silverpeas.com")).thenReturn(Boolean.TRUE); MessageListener mockListener2 = mock(MessageListener.class); Map<String, MessageListener> listenersByEmail = new HashMap<String, MessageListener>(2); listenersByEmail.put("thesimpsons@silverpeas.com", mockListener1); listenersByEmail.put("theflanders@silverpeas.com", mockListener2); MimeMessage mail = new MimeMessage(messageChecker.getMailSession()); InternetAddress bart = new InternetAddress("bart.simpson@silverpeas.com"); InternetAddress theSimpsons = new InternetAddress("thesimpsons@silverpeas.com"); mail.addFrom(new InternetAddress[] { bart }); mail.addRecipient(RecipientType.TO, theSimpsons); mail.setSubject("Simple html Email test"); String html = loadHtml();/*from w ww .ja v a 2 s . com*/ mail.setText(html, "UTF-8", "html"); mail.setSentDate(new Date()); Date sentDate = new Date(mail.getSentDate().getTime()); Transport.send(mail); Map<MessageListener, MessageEvent> events = new HashMap<MessageListener, MessageEvent>(); messageChecker.processEmail(mail, events, listenersByEmail); assertNotNull(events); assertEquals(1, events.size()); assertNull(events.get(mockListener2)); MessageEvent event = events.get(mockListener1); assertNotNull(event); assertNotNull(event.getMessages()); assertEquals(1, event.getMessages().size()); Message message = event.getMessages().get(0); assertEquals("bart.simpson@silverpeas.com", message.getSender()); assertEquals("Simple html Email test", message.getTitle()); assertEquals(html, message.getBody()); assertNotNull(message.getSentDate()); assertEquals(sentDate.getTime(), message.getSentDate().getTime()); assertEquals(htmlEmailSummary, message.getSummary()); assertEquals(0, message.getAttachmentsSize()); assertEquals(0, message.getAttachments().size()); assertEquals("componentId", message.getComponentId()); assertEquals("text/html; charset=UTF-8", message.getContentType()); verify(mockListener1, atLeastOnce()).checkSender("bart.simpson@silverpeas.com"); }
From source file:org.medici.bia.service.mail.MailServiceImpl.java
/** * {@inheritDoc}/*from w ww . j ava 2 s . c o m*/ */ @Transactional(readOnly = false, propagation = Propagation.REQUIRED) @Override public Boolean sendEmailMessageUser(final EmailMessageUser emailMessageUser) { try { if (!StringUtils.isBlank(emailMessageUser.getUser().getMail())) { // SimpleMailMessage message = new SimpleMailMessage(); // message.setFrom(getMailFrom()); // message.setTo(emailMessageUser.getUser().getMail()); // message.setSubject(emailMessageUser.getSubject()); // message.setText(emailMessageUser.getBody()); MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { mimeMessage.setFrom(new InternetAddress(getMailFrom())); mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(emailMessageUser.getUser().getMail())); mimeMessage.setSubject(emailMessageUser.getSubject()); mimeMessage.setText(emailMessageUser.getBody(), "utf-8", "html"); } }; getJavaMailSender().send(preparator); emailMessageUser.setMailSended(Boolean.TRUE); emailMessageUser.setMailSendedDate(new Date()); getEmailMessageUserDAO().merge(emailMessageUser); } else { logger.error("Email message not sended for user " + emailMessageUser.getUser().getAccount() + ". Check mail field on tblUser for account " + emailMessageUser.getUser().getAccount()); } return Boolean.TRUE; } catch (Throwable throwable) { logger.error(throwable); return Boolean.FALSE; } }
From source file:org.projectforge.mail.SendMail.java
private void sendIt(final Mail composedMessage) { final Session session = Session.getInstance(properties); Transport transport = null;// w w w . j a v a 2 s . c om try { MimeMessage message = new MimeMessage(session); if (composedMessage.getFrom() != null) { message.setFrom(new InternetAddress(composedMessage.getFrom())); } else { message.setFrom(); } message.setRecipients(Message.RecipientType.TO, composedMessage.getTo()); String subject; subject = composedMessage.getSubject(); /* * try { subject = MimeUtility.encodeText(composedMessage.getSubject()); } catch (UnsupportedEncodingException ex) { * log.error("Exception encountered while encoding subject." + ex, ex); subject = composedMessage.getSubject(); } */ message.setSubject(subject, sendMailConfig.getCharset()); message.setSentDate(new Date()); if (composedMessage.getContentType() != null) { message.setText(composedMessage.getContent(), composedMessage.getCharset(), composedMessage.getContentType()); } else { message.setText(composedMessage.getContent(), sendMailConfig.getCharset()); } message.saveChanges(); // don't forget this transport = session.getTransport(); if (StringUtils.isNotEmpty(sendMailConfig.getUser()) == true) { transport.connect(sendMailConfig.getUser(), sendMailConfig.getPassword()); } else { transport.connect(); } transport.sendMessage(message, message.getAllRecipients()); } catch (MessagingException ex) { log.error("While creating and sending message: " + composedMessage.toString(), ex); throw new InternalErrorException("mail.error.exception"); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException ex) { log.error("While creating and sending message: " + composedMessage.toString(), ex); throw new InternalErrorException("mail.error.exception"); } } } log.info("E-Mail successfully sent: " + composedMessage.toString()); }
From source file:cc.kune.core.server.mail.MailServiceDefault.java
@Override public void send(final String from, final AbstractFormattedString subject, final AbstractFormattedString body, final boolean isHtml, final String... tos) { if (smtpSkip) { return;/* ww w. j a v a2 s . c o m*/ } // Get session final Session session = Session.getDefaultInstance(props, null); // Define message final MimeMessage message = new MimeMessage(session); for (final String to : tos) { try { message.setFrom(new InternetAddress(from)); // In case we should use utf8 also in address: // http://stackoverflow.com/questions/2656478/send-javax-mail-internet-mimemessage-to-a-recipient-with-non-ascii-name message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // If additional header should be added // message.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B")); final String formatedSubject = subject.getString(); message.setSubject(formatedSubject, "utf-8"); final String formatedBody = body.getString(); if (isHtml) { // message.setContent(formatedBody, "text/html"); message.setText(formatedBody, "UTF-8", "html"); } else { message.setText(formatedBody, "UTF-8"); } // Send message Transport.send(message); } catch (final AddressException e) { } catch (final MessagingException e) { final String error = String.format("Error sendind an email to %s, with subject: %s, and body: %s", from, subject, to); log.error(error, e); // Better not to throw exceptions because users emails can be wrong... // throw new DefaultException(error, e); } } }
From source file:trendplot.TrendPlot.java
private void emailResults() throws IOException, WebUtilException { emailStart = System.currentTimeMillis(); ViewerConfig vc = new ViewerConfig(); if (!config.isEmpty()) { vc.setConfigFileName(config);//ww w . ja v a 2s . c o m } vc.readConfig(); String host = vc.get("webserver"); if (host == null || host.isEmpty()) { host = "ldvw.ligo.caltech.edu"; } String servlet = vc.get("servlet"); if (servlet == null || servlet.isEmpty()) { servlet = "ldvw/view"; } PageItemList msg = new PageItemList(); if (!imgIds.isEmpty()) { msg.add(new PageItemHeader("The following results are available:", 3)); PageTable tbl = new PageTable(); for (int img = 0; img < imgIds.size(); img++) { PageTableRow row = new PageTableRow(); row.add(descriptions.get(img)); Integer imgId = imgIds.get(img); String url = "https://" + host + "/" + servlet + "?act=getimg&imgId=" + imgId.toString(); PageItemTextLink link = new PageItemTextLink(url, "link"); row.add(link); tbl.addRow(row); } msg.add(tbl); msg.addBlankLines(2); String groupIntro = String.format("These images have also been added to the %1$s group.<br>", group); msg.add(new PageItemString(groupIntro, false)); String groupUrl = String.format( "https://%1$s/%2$s?act=imagehistory&group=%3$s" + "&usrSel=%4$s", host, servlet, group, user); PageItemTextLink groupLink = new PageItemTextLink(groupUrl, "Click for image group page."); msg.add(groupLink); msg.addBlankLines(2); } else if (!checkOnly) { msg.add("Sorry but no images were produced."); msg.addBlankLines(2); } if (verbose || imgIds.isEmpty()) { msg.add(new PageItemString("<br>Stdout:<br><br>", false)); String outText = outStringWriter.toString().replace("\n", "<br>\n"); msg.add(new PageItemString(outText, false)); msg.add(new PageItemString("<br>Stderr:<br><br>", false)); outText = errStringWriter.toString().replace("\n", "<br>\n"); msg.add(new PageItemString(outText, false)); } msg.add(new PageItemString("<br><br>Sincerly,<br>The LigoDV-web group", false)); Float condor = (startTime - qtime) / 1000.f; String condorTime = qtime == 0 ? "?" : String.format("%1$.2f", condor); Float overhead = (transferStart - startTime) / 1000.f; Float xfer = (plotStart - transferStart) / 1000.f; Float plot = (emailStart - plotStart) / 1000.f; String timing = String.format( "Timing: queue: %1$s, overhead: %2$.2f, data collection: %3$.2f, " + "plot: %4$.2f seconds", condorTime, overhead, xfer, plot); outPrintWriter.println(timing); msg.addBlankLines(2); msg.add(new PageItemString(timing, false)); msg.addBlankLines(1); String msgText = msg.getHtml(); Properties fMailServerConfig; fMailServerConfig = new Properties(); fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu"); fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu"); Session session = Session.getDefaultInstance(fMailServerConfig, null); MimeMessage message = new MimeMessage(session); try { //the "from" address may be set in code, or set in the //config file under "mail.from" ; here, the latter style is used message.setFrom(new InternetAddress("areeda@ligo.caltech.edu")); message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); message.setSubject("Trend plot results are available."); message.setText(msgText, "utf-8", "html"); Transport.send(message); outPrintWriter.format("Email sent to %1$s\n", email); errPrintWriter.println("Email message:"); errPrintWriter.println(msgText); } catch (MessagingException ex) { throw new WebUtilException("Cannot send email. " + ex); } }
From source file:trendplot.TrendPlot.java
private void testEmail() { Properties fMailServerConfig; fMailServerConfig = new Properties(); fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu"); fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu"); Session session = Session.getDefaultInstance(fMailServerConfig, null); MimeMessage message = new MimeMessage(session); try {//www.j av a 2 s . com //the "from" address may be set in code, or set in the //config file under "mail.from" ; here, the latter style is used message.setFrom(new InternetAddress("areeda@ligo.caltech.edu")); String email = "joe@areeda.com"; message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); String msg = "<h3>this is a test</h3>"; message.setSubject("Test email"); message.setText(msg, "utf-8", "html"); Transport.send(message); System.out.format("Email sent to %1$s\n", email); } catch (MessagingException ex) { System.err.format("Exception: %1$s: %2$s", ex.getClass().getSimpleName(), ex.getLocalizedMessage()); } }
From source file:com.azprogrammer.qgf.controllers.HomeController.java
@RequestMapping(value = "/wbmail") public ModelAndView doWhiteboardMail(ModelMap model, HttpServletRequest req) { model.clear();// w w w. j a v a2 s. com try { WBEmail email = new WBEmail(); HttpSession session = req.getSession(); String userName = session.getAttribute("userName").toString(); String toAddress = req.getParameter("email"); if (!WebUtil.isValidEmail(toAddress)) { throw new Exception("invalid email"); } //TODO validate message contents email.setFromUser(userName); email.setToAddress(toAddress); WhiteBoard wb = getWhiteBoard(req); if (wb == null) { throw new Exception("Invalid White Board"); } email.setWbKey(wb.getKey()); email.setCreationTime(System.currentTimeMillis()); Properties props = new Properties(); Session mailsession = Session.getDefaultInstance(props, null); String emailError = null; try { MimeMessage msg = new MimeMessage(mailsession); msg.setFrom(new InternetAddress("no_reply@drawitlive.com", "Draw it Live")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); msg.setSubject("Please join the whiteboard session on " + req.getServerName()); String msgBody = "To join " + userName + " on a colloborative whiteboard follow this link: <a href=\"http://" + req.getServerName() + "/whiteboard/" + req.getParameter("wbId") + "\"> http://" + req.getServerName() + "/whiteboard/" + req.getParameter("wbId") + "</a>"; msg.setText(msgBody, "UTF-8", "html"); Transport.send(msg); } catch (AddressException e) { emailError = e.getMessage(); } catch (MessagingException e) { emailError = e.getMessage(); } if (emailError == null) { email.setStatus(WBEmail.STATUS_SENT); } else { email.setStatus(WBEmail.STATUS_ERROR); } getPM().makePersistent(email); if (email.getStatus() == WBEmail.STATUS_ERROR) { throw new Exception(emailError); } model.put("status", "ok"); } catch (Exception e) { model.put("error", e.getMessage()); } return doJSON(model); }