List of usage examples for javax.mail Transport send
public static void send(Message msg) throws MessagingException
From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java
@Override public void sendNotification(String smtpSender, String replyTo, String recipient, String subject, String htmlContent, String inReplyTo, String references) throws SendFailedException { if (smtpServer.equals("")) { logger.warn("Mail notifications are disabled."); return;/* www . j a v a2 s .c o m*/ } // get the mail session Session session = getMailSession(); // Define message MimeMessage messageMim = new MimeMessage(session); try { messageMim.setFrom(new InternetAddress(smtpSender)); if (replyTo != null) { InternetAddress reply[] = new InternetAddress[1]; reply[0] = new InternetAddress(replyTo); messageMim.setReplyTo(reply); } messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); if (inReplyTo != null && inReplyTo != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(inReplyTo)) { messageMim.setHeader("In-Reply-To", inReplyTo); } } if (references != null && references != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(references)) { messageMim.setHeader("References", references); } } messageMim.setSubject(subject, charset); // Create a "related" Multipart message // content type is multipart/alternative // it will contain two part BodyPart 1 and 2 Multipart mp = new MimeMultipart("alternative"); // BodyPart 2 // content type is multipart/related // A multipart/related is used to indicate that message parts should // not be considered individually but rather // as parts of an aggregate whole. The message consists of a root // part (by default, the first) which reference other parts inline, // which may in turn reference other parts. Multipart html_mp = new MimeMultipart("related"); // Include an HTML message with images. // BodyParts: the HTML file and an image // Get the HTML file BodyPart rel_bph = new MimeBodyPart(); rel_bph.setDataHandler( new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset))); html_mp.addBodyPart(rel_bph); // Create the second BodyPart of the multipart/alternative, // set its content to the html multipart, and add the // second bodypart to the main multipart. BodyPart alt_bp2 = new MimeBodyPart(); alt_bp2.setContent(html_mp); mp.addBodyPart(alt_bp2); messageMim.setContent(mp); // RFC 822 "Date" header field // Indicates that the message is complete and ready for delivery messageMim.setSentDate(new GregorianCalendar().getTime()); // Since we used html tags, the content must be marker as text/html // messageMim.setContent(content,"text/html; charset="+charset); Transport tr = session.getTransport("smtp"); // Connect to smtp server, if needed if (needsAuth) { tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword); messageMim.saveChanges(); tr.sendMessage(messageMim, messageMim.getAllRecipients()); tr.close(); } else { // Send message Transport.send(messageMim); } } catch (SendFailedException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient, e); throw e; } catch (MessagingException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } catch (Exception e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } }
From source file:com.nokia.helium.core.EmailDataSender.java
/** * Send xml data//from w ww. j a v a 2s.c o m * * @param String purpose of this email * @param String file to send * @param String mime type * @param String subject of email * @param String header of mail * @param boolean compress data if true */ public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header, boolean compressData) throws EmailSendException { try { log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType); if (fileToSend != null && fileToSend.exists()) { InternetAddress[] toAddresses = getToAddressList(); Properties props = new Properties(); if (smtpServerAddress != null) { log.debug("sendData:smtp address: " + smtpServerAddress); props.setProperty("mail.smtp.host", smtpServerAddress); } Session mailSession = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(mailSession); message.setSubject(subject == null ? "" : subject); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); ByteArrayDataSource dataSrc = null; String fileName = fileToSend.getName(); if (compressData) { log.debug("Sending compressed data"); dataSrc = compressFile(fileToSend); dataSrc.setName(fileName + ".gz"); messageBodyPart.setFileName(fileName + ".gz"); } else { log.debug("Sending uncompressed data:"); dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType); message.setContent(FileUtils.readFileToString(fileToSend), "text/html"); multipart = null; } String headerToSend = null; if (header == null) { headerToSend = ""; } messageBodyPart.setHeader("helium-bld-data", headerToSend); messageBodyPart.setDataHandler(new DataHandler(dataSrc)); if (multipart != null) { multipart.addBodyPart(messageBodyPart); // add to the // multipart message.setContent(multipart); } try { message.setFrom(getFromAddress()); } catch (AddressException e) { throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e); } catch (LDAPException e) { throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e); } message.addRecipients(Message.RecipientType.TO, toAddresses); log.info("Sending email alert: " + subject); Transport.send(message); } } catch (MessagingException e) { String fullErrorMessage = "Failed sending e-mail: " + purpose; if (e.getMessage() != null) { fullErrorMessage += ": " + e.getMessage(); } throw new EmailSendException(fullErrorMessage, e); } catch (IOException e) { String fullErrorMessage = "Failed sending e-mail: " + purpose; if (e.getMessage() != null) { fullErrorMessage += ": " + e.getMessage(); } // We are Ignoring the errors as no need to fail the build. throw new EmailSendException(fullErrorMessage, e); } }
From source file:Mailer.java
/** Send the message. *///from ww w . jav a2 s . c o m public synchronized void doSend() throws MessagingException { if (!isComplete()) throw new IllegalArgumentException("doSend called before message was complete"); /** Properties object used to pass props into the MAIL API */ Properties props = new Properties(); props.put("mail.smtp.host", mailHost); // Create the Session object if (session == null) { session = Session.getDefaultInstance(props, null); if (verbose) session.setDebug(true); // Verbose! } // create a message final Message mesg = new MimeMessage(session); InternetAddress[] addresses; // TO Address list addresses = new InternetAddress[toList.size()]; for (int i = 0; i < addresses.length; i++) addresses[i] = new InternetAddress((String) toList.get(i)); mesg.setRecipients(Message.RecipientType.TO, addresses); // From Address mesg.setFrom(new InternetAddress(from)); // CC Address list addresses = new InternetAddress[ccList.size()]; for (int i = 0; i < addresses.length; i++) addresses[i] = new InternetAddress((String) ccList.get(i)); mesg.setRecipients(Message.RecipientType.CC, addresses); // BCC Address list addresses = new InternetAddress[bccList.size()]; for (int i = 0; i < addresses.length; i++) addresses[i] = new InternetAddress((String) bccList.get(i)); mesg.setRecipients(Message.RecipientType.BCC, addresses); // The Subject mesg.setSubject(subject); // Now the message body. mesg.setText(body); // Finally, send the message! (use static Transport method) // Do this in a Thread as it sometimes is too slow for JServ // new Thread() { // public void run() { // try { Transport.send(mesg); // } catch (MessagingException e) { // throw new IllegalArgumentException( // "Transport.send() threw: " + e.toString()); // } // } // }.start(); }
From source file:com.appeligo.search.messenger.Messenger.java
/** * //w w w . j av a 2 s .co m * @param messages */ public int send(com.appeligo.search.entity.Message... messages) { int sent = 0; if (messages == null) { return 0; } for (com.appeligo.search.entity.Message message : messages) { User user = message.getUser(); if (user != null) { boolean changed = false; boolean abort = false; if ((!user.isEnabled()) || (!user.isRegistrationComplete()) || (message.isSms() && (!user.isSmsValid()))) { abort = true; if (message.getExpires() == null) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.HOUR, 24); message.setExpires(new Timestamp(cal.getTimeInMillis())); changed = true; } } if (message.isSms() && user.isSmsValid() && (!user.isSmsOKNow())) { Calendar now = Calendar.getInstance(user.getTimeZone()); now.set(Calendar.MILLISECOND, 0); now.set(Calendar.SECOND, 0); Calendar nextWindow = Calendar.getInstance(user.getTimeZone()); nextWindow.setTime(user.getEarliestSmsTime()); nextWindow.set(Calendar.MILLISECOND, 0); nextWindow.set(Calendar.SECOND, 0); nextWindow.add(Calendar.MINUTE, 1); // compensate for zeroing out millis, seconds nextWindow.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE)); int nowMinutes = (now.get(Calendar.HOUR) * 60) + now.get(Calendar.MINUTE); int nextMinutes = (nextWindow.get(Calendar.HOUR) * 60) + nextWindow.get(Calendar.MINUTE); if (nowMinutes > nextMinutes) { nextWindow.add(Calendar.HOUR, 24); } message.setDeferUntil(new Timestamp(nextWindow.getTimeInMillis())); changed = true; abort = true; } if (changed) { message.save(); } if (abort) { continue; } } String to = message.getTo(); String from = message.getFrom(); String subject = message.getSubject(); String body = message.getBody(); String contentType = message.getMimeType(); try { Properties props = new Properties(); //Specify the desired SMTP server props.put("mail.smtp.host", mailHost); props.put("mail.smtp.port", Integer.toString(port)); // create a new Session object Session session = null; if (password != null) { props.put("mail.smtp.auth", "true"); session = Session.getInstance(props, new SMTPAuthenticator(smtpUser, password)); } else { session = Session.getInstance(props, null); } session.setDebug(debug); // create a new MimeMessage object (using the Session created above) Message mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, new InternetAddress[] { new InternetAddress(to) }); mimeMessage.setSubject(subject); mimeMessage.setContent(body.toString(), contentType); if (mailHost.trim().equals("")) { log.info("No Mail Host. Would have sent:"); log.info("From: " + from); log.info("To: " + to); log.info("Subject: " + subject); log.info(mimeMessage.getContent()); } else { Transport.send(mimeMessage); sent++; } message.setSent(new Date()); } catch (Throwable t) { message.failedAttempt(); if (message.getAttempts() >= maxAttempts) { message.setExpires(new Timestamp(System.currentTimeMillis())); } log.error(t.getMessage(), t); } } return sent; }
From source file:contestWebsite.ContactUs.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Query query = new Query("user") .setFilter(new FilterPredicate("name", FilterOperator.EQUAL, req.getParameter("name"))); List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(3)); Entity feedback = new Entity("feedback"); if (users.size() != 0) { feedback.setProperty("user-id", users.get(0).getProperty("user-id")); }/* w w w .jav a 2s . c o m*/ String name = escapeHtml4(req.getParameter("name")); String school = escapeHtml4(req.getParameter("school")); String comment = escapeHtml4(req.getParameter("text")); String email = escapeHtml4(req.getParameter("email")); HttpSession sess = req.getSession(true); sess.setAttribute("name", name); sess.setAttribute("school", school); sess.setAttribute("email", email); sess.setAttribute("comment", comment); Entity contestInfo = Retrieve.contestInfo(); if (!(Boolean) sess.getAttribute("nocaptcha")) { URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify"); String charset = java.nio.charset.StandardCharsets.UTF_8.name(); String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s", URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset), URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset), URLEncoder.encode(req.getRemoteAddr(), charset)); final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection(); connection.setRequestProperty("Accept-Charset", charset); String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() { @Override public InputStream getInput() throws IOException { return connection.getInputStream(); } }, Charsets.UTF_8)); try { JSONObject JSONResponse = new JSONObject(response); if (!JSONResponse.getBoolean("success")) { resp.sendRedirect("/contactUs?captchaError=1"); return; } } catch (JSONException e) { e.printStackTrace(); resp.sendRedirect("/contactUs?captchaError=1"); return; } } feedback.setProperty("name", name); feedback.setProperty("school", school); feedback.setProperty("email", email); feedback.setProperty("comment", new Text(comment)); feedback.setProperty("resolved", false); Transaction txn = datastore.beginTransaction(); try { datastore.put(feedback); txn.commit(); Session session = Session.getDefaultInstance(new Properties(), null); String appEngineEmail = (String) contestInfo.getProperty("account"); try { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress((String) contestInfo.getProperty("email"), "Contest Administrator")); msg.setSubject("Question about tournament from " + name); msg.setReplyTo(new InternetAddress[] { new InternetAddress(req.getParameter("email"), name), new InternetAddress(appEngineEmail, "Tournament Website Admin") }); VelocityEngine ve = new VelocityEngine(); ve.init(); VelocityContext context = new VelocityContext(); context.put("name", name); context.put("email", email); context.put("school", school); context.put("message", comment); StringWriter sw = new StringWriter(); Velocity.evaluate(context, sw, "questionEmail", ((Text) contestInfo.getProperty("questionEmail")).getValue()); msg.setContent(sw.toString(), "text/html"); Transport.send(msg); } catch (MessagingException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } resp.sendRedirect("/contactUs?updated=1"); sess.invalidate(); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } }
From source file:de.betterform.connector.smtp.SMTPSubmissionHandler.java
private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception { URL url = new URL(uri); String recipient = url.getPath(); String server = null;/*from w w w .j ava 2 s. co m*/ String port = null; String sender = null; String subject = null; String username = null; String password = null; StringTokenizer headers = new StringTokenizer(url.getQuery(), "&"); while (headers.hasMoreTokens()) { String token = headers.nextToken(); if (token.startsWith("server=")) { server = URLDecoder.decode(token.substring("server=".length()), "UTF-8"); continue; } if (token.startsWith("port=")) { port = URLDecoder.decode(token.substring("port=".length()), "UTF-8"); continue; } if (token.startsWith("sender=")) { sender = URLDecoder.decode(token.substring("sender=".length()), "UTF-8"); continue; } if (token.startsWith("subject=")) { subject = URLDecoder.decode(token.substring("subject=".length()), "UTF-8"); continue; } if (token.startsWith("username=")) { username = URLDecoder.decode(token.substring("username=".length()), "UTF-8"); continue; } if (token.startsWith("password=")) { password = URLDecoder.decode(token.substring("password=".length()), "UTF-8"); continue; } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("smtp server '" + server + "'"); if (username != null) { LOGGER.debug("smtp-auth username '" + username + "'"); } LOGGER.debug("mail sender '" + sender + "'"); LOGGER.debug("subject line '" + subject + "'"); } Properties properties = System.getProperties(); properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled())); properties.put("mail.smtp.from", sender); properties.put("mail.smtp.host", server); if (port != null) { properties.put("mail.smtp.port", port); } if (username != null) { properties.put("mail.smtp.auth", String.valueOf(true)); properties.put("mail.smtp.user", username); } Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password)); MimeMessage message = null; if (mediatype.startsWith("multipart/")) { message = new MimeMessage(session, new ByteArrayInputStream(data)); } else { message = new MimeMessage(session); if (mediatype.toLowerCase().indexOf("charset=") == -1) { mediatype += "; charset=\"" + encoding + "\""; } message.setText(new String(data, encoding), encoding); message.setHeader("Content-Type", mediatype); } message.setRecipient(RecipientType.TO, new InternetAddress(recipient)); message.setSubject(subject); message.setSentDate(new Date()); Transport.send(message); }
From source file:org.unitime.commons.Email.java
public void send() throws MessagingException, UnsupportedEncodingException { long t0 = System.currentTimeMillis(); try {/* w ww .ja v a2 s .c o m*/ setFrom(ApplicationProperties.getProperty("unitime.email.sender", ApplicationProperties.getProperty("tmtbl.inquiry.sender", ApplicationProperties.getProperty("tmtbl.contact.email"))), ApplicationProperties.getProperty("unitime.email.sender.name", ApplicationProperties.getProperty("tmtbl.inquiry.sender.name", ApplicationProperties .getProperty("tmtbl.contact.email.name", "UniTime Email")))); if (iMail.getReplyTo() == null || iMail.getReplyTo().length == 0) setReplyTo(ApplicationProperties.getProperty("unitime.email.replyto"), ApplicationProperties.getProperty("unitime.email.replyto.name")); iMail.setSentDate(new Date()); iMail.setContent(iBody); iMail.saveChanges(); Transport.send(iMail); } finally { long t = System.currentTimeMillis() - t0; if (t > 30000) sLog.warn("It took " + new DecimalFormat("0.00").format(t / 1000.0) + " seconds to send an email."); else if (t > 5000) sLog.info("It took " + new DecimalFormat("0.00").format(t / 1000.0) + " seconds to send an email."); } }
From source file:com.enonic.esl.net.Mail.java
/** * <p/> Send the mail. The SMTP host is contacted and the mail is sent according to the parameters set. </p> <p/> If it fails, it is * considered a runtime exception. Note that this doesn't make it very failsafe, so care should be taken when one wants fault tolerance. * One solution could be to catch the exception thrown. Another solution could be to use the JavaMail API directly. </p> *//*w ww .j a v a 2s.com*/ public void send() throws ESLException { // smtp server Properties smtpProperties = new Properties(); if (smtpHost != null) { smtpProperties.put("mail.smtp.host", smtpHost); System.setProperty("mail.smtp.host", smtpHost); } else { smtpProperties.put("mail.smtp.host", DEFAULT_SMTPHOST); System.setProperty("mail.smtp.host", DEFAULT_SMTPHOST); } Session session = Session.getDefaultInstance(smtpProperties, null); try { // create message Message msg = new MimeMessage(session); // set from address InternetAddress addressFrom = new InternetAddress(); if (from_email != null) { addressFrom.setAddress(from_email); } if (from_name != null) { addressFrom.setPersonal(from_name, ENCODING); } ((MimeMessage) msg).setFrom(addressFrom); if ((to.size() == 0 && bcc.size() == 0) || subject == null || (message == null && htmlMessage == null)) { LOG.error("Missing data. Unable to send mail."); throw new ESLException("Missing data. Unable to send mail."); } // set to: for (int i = 0; i < to.size(); ++i) { String[] recipient = to.get(i); InternetAddress addressTo = new InternetAddress(recipient[1]); if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.TO, addressTo); } // set bcc: for (int i = 0; i < bcc.size(); ++i) { String[] recipient = bcc.get(i); InternetAddress addressTo = null; try { addressTo = new InternetAddress(recipient[1]); } catch (Exception e) { System.err.println("exception on address: " + recipient[1]); continue; } if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.BCC, addressTo); } // set cc: for (int i = 0; i < cc.size(); ++i) { String[] recipient = cc.get(i); InternetAddress addressTo = new InternetAddress(recipient[1]); if (recipient[0] != null) { addressTo.setPersonal(recipient[0], ENCODING); } ((MimeMessage) msg).addRecipient(Message.RecipientType.CC, addressTo); } // Setting subject and content type ((MimeMessage) msg).setSubject(subject, ENCODING); if (message != null) { message = RegexpUtil.substituteAll("\\\\n", "\n", message); } // if there are any attachments, treat this as a multipart message. if (attachments.size() > 0) { BodyPart messageBodyPart = new MimeBodyPart(); if (message != null) { ((MimeBodyPart) messageBodyPart).setText(message, ENCODING); } else { DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(htmlMessage, "text/html", ENCODING)); ((MimeBodyPart) messageBodyPart).setDataHandler(dataHandler); } Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // add all attachments for (int i = 0; i < attachments.size(); ++i) { Object obj = attachments.get(i); if (obj instanceof String) { System.err.println("attachment is String"); messageBodyPart = new MimeBodyPart(); ((MimeBodyPart) messageBodyPart).setText((String) obj, ENCODING); multipart.addBodyPart(messageBodyPart); } else if (obj instanceof File) { messageBodyPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource((File) obj); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setFileName(fds.getName()); multipart.addBodyPart(messageBodyPart); } else if (obj instanceof FileItem) { FileItem fileItem = (FileItem) obj; messageBodyPart = new MimeBodyPart(); FileItemDataSource fds = new FileItemDataSource(fileItem); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setFileName(fds.getName()); multipart.addBodyPart(messageBodyPart); } else { // byte array messageBodyPart = new MimeBodyPart(); ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) obj, "text/html", ENCODING); messageBodyPart.setDataHandler(new DataHandler(bads)); messageBodyPart.setFileName(bads.getName()); multipart.addBodyPart(messageBodyPart); } } msg.setContent(multipart); } else { if (message != null) { ((MimeMessage) msg).setText(message, ENCODING); } else { DataHandler dataHandler = new DataHandler( new ByteArrayDataSource(htmlMessage, "text/html", ENCODING)); ((MimeMessage) msg).setDataHandler(dataHandler); } } // send message Transport.send(msg); } catch (AddressException e) { String MESSAGE_30 = "Error in email address: " + e.getMessage(); LOG.warn(MESSAGE_30); throw new ESLException(MESSAGE_30, e); } catch (UnsupportedEncodingException e) { String MESSAGE_40 = "Unsupported encoding: " + e.getMessage(); LOG.error(MESSAGE_40, e); throw new ESLException(MESSAGE_40, e); } catch (SendFailedException sfe) { Throwable t = null; Exception e = sfe.getNextException(); while (e != null) { t = e; if (t instanceof SendFailedException) { e = ((SendFailedException) e).getNextException(); } else { e = null; } } if (t != null) { String MESSAGE_50 = "Error sending mail: " + t.getMessage(); throw new ESLException(MESSAGE_50, t); } else { String MESSAGE_50 = "Error sending mail: " + sfe.getMessage(); throw new ESLException(MESSAGE_50, sfe); } } catch (MessagingException e) { String MESSAGE_50 = "Error sending mail: " + e.getMessage(); LOG.error(MESSAGE_50, e); throw new ESLException(MESSAGE_50, e); } }
From source file:com.brienwheeler.svc.email.impl.EmailService.java
/** * This is a private method (rather than having the public template method * call the public non-template method) to prevent inaccurate MonitoredWork * operation counts./* w ww .ja va 2 s . com*/ * * @param recipient * @param subject * @param body */ private void doSendEmail(EmailAddress recipient, String subject, String body) { ValidationUtils.assertNotNull(recipient, "recipient cannot be null"); subject = ValidationUtils.assertNotEmpty(subject, "subject cannot be empty"); body = ValidationUtils.assertNotEmpty(body, "body cannot be empty"); try { MimeMessage message = new MimeMessage(mailSession); message.setFrom(new InternetAddress(fromAddress.getAddress())); message.setRecipients(Message.RecipientType.TO, recipient.getAddress()); message.setSubject(subject); message.setSentDate(new Date()); message.setText(body); Transport.send(message); log.info("sent email to " + recipient.getAddress() + " (" + subject + ")"); } catch (MessagingException e) { throw new ServiceOperationException(e); } }
From source file:io.uengine.mail.MailAsyncService.java
@Async public void registe(Long userId, String token, String subject, String fromUser, String fromName, final String toUser, InternetAddress[] toCC) { Session session = setMailProperties(toUser); Map model = new HashMap(); model.put("link", MessageFormatter.arrayFormat("http://www.uengine.io/registe/confirm?userid={}&token={}", new Object[] { Long.toString(userId), token }).getMessage()); String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/registe.vm", "UTF-8", model);/* ww w .j a v a 2 s . c o m*/ try { InternetAddress from = new InternetAddress(fromUser, fromName); MimeMessage message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser)); message.setSubject(subject); message.setContent(body, "text/html; charset=utf-8"); if (toCC != null && toCC.length > 0) message.setRecipients(Message.RecipientType.CC, toCC); Transport.send(message); logger.info("{} ? ?? .", toUser); } catch (Exception e) { throw new ServiceException("?? .", e); } }