List of usage examples for javax.mail Message setContent
public void setContent(Object obj, String type) throws MessagingException;
From source file:it.cnr.icar.eric.server.event.EmailNotifier.java
private void postMail(String endpoint, String message, String subject, String contentType) throws MessagingException { // get the SMTP address String smtpHost = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.host"); // get the FROM address String fromAddress = RegistryProperties.getInstance() .getProperty("eric.server.event.EmailNotifier.smtp.from", "eric@localhost"); // get the TO address that follows 'mailto:' String recipient = endpoint.substring(7); String smtpPort = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.port", null);// w w w.j ava2 s. c o m String smtpAuth = RegistryProperties.getInstance().getProperty("eric.server.event.EmailNotifier.smtp.auth", null); String smtpDebug = RegistryProperties.getInstance() .getProperty("eric.server.event.EmailNotifier.smtp.debug", "false"); //Set the host smtp address Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.debug", smtpDebug); props.put("mail.smtp.host", smtpHost); if ((smtpPort != null) && (smtpPort.length() > 0)) { props.put("mail.smtp.port", smtpPort); } Session session; if ("tls".equals(smtpAuth)) { // get the username String userName = RegistryProperties.getInstance() .getProperty("eric.server.event.EmailNotifier.smtp.user", null); String password = RegistryProperties.getInstance() .getProperty("eric.server.event.EmailNotifier.smtp.password", null); Authenticator authenticator = new MyAuthenticator(userName, password); props.put("mail.user", userName); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); session = Session.getInstance(props, authenticator); } else { session = Session.getInstance(props); } session.setDebug(Boolean.valueOf(smtpDebug).booleanValue()); // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(fromAddress); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[1]; addressTo[0] = new InternetAddress(recipient); msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, contentType); Transport.send(msg); }
From source file:com.cloudbees.demo.beesshop.service.MailService.java
public void sendOrderConfirmation(ShoppingCart shoppingCart, String recipient) { try {/*from www . j a v a2 s. c om*/ Message msg = new MimeMessage(mailSession); msg.setFrom(fromAddress); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); msg.setSubject("[BeesShop] Order Confirmation: " + shoppingCart.getItems() + " items - " + shoppingCart.getPrettyPrice()); String message = "ORDER CONFIRMATION\n" + "\n" + "* Purchased items: " + shoppingCart.getItemsCount() + "\n" + "* Price: " + shoppingCart.getPrettyPrice() + "\n"; for (ShoppingCart.ShoppingCartItem item : shoppingCart.getItems()) { message += " * " + item.getQuantity() + "x" + item.getProduct().getName() + "\n"; } msg.setContent(message, "text/plain"); Transport.send(msg); auditLogger.info("Sent to {} shopping cart with value of '{}'", recipient, shoppingCart.getPrettyPrice()); sentEmailCounter.incrementAndGet(); } catch (MessagingException e) { logger.warn("Exception sending order confirmation email to {}", recipient, e); } }
From source file:com.app.mail.DefaultMailSender.java
private Message _populateMessage(String emailAddress, String subject, String template, Session session) throws Exception { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS, "Auction Alert")); message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress)); message.setSubject(subject);/*from w ww .j av a2 s. c o m*/ Map<String, Object> rootMap = new HashMap<>(); rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME); String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine, "template/" + template, "UTF-8", rootMap); message.setContent(messageBody, "text/html"); return message; }
From source file:com.photon.phresco.util.Utility.java
public static void sendNewPassword(String[] toAddr, String fromAddr, String user, String subject, String body, String username, String password, String host, String screen, String build) throws PhrescoException { List<String> lists = Arrays.asList(toAddr); if (fromAddr == null) { fromAddr = "phresco.do.not.reply@gmail.com"; username = "phresco.do.not.reply@gmail.com"; password = "phresco123"; }/*from ww w . j av a 2 s . co m*/ Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getDefaultInstance(props, new LoginAuthenticator(username, password)); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddr)); List<Address> emailsList = getEmailsList(lists); Address[] dsf = new Address[emailsList.size()]; message.setRecipients(Message.RecipientType.BCC, emailsList.toArray(dsf)); message.setSubject(subject); message.setContent(body, "text/html"); Transport.send(message); } catch (MessagingException e) { throw new PhrescoException(e); } }
From source file:com.sfs.ucm.service.MailService.java
/** * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager. * // w w w . ja v a 2 s . co m * @param fromAddress * @param recipients * - fully qualified recipient address * @param subject * @param body * @param messageType * - text/plain or text/html * @throws IllegalArgumentException */ @Asynchronous public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String[] toRecipients, final String subject, final String body, final String messageType) { // argument validation if (fromAddress == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress"); } if (toRecipients == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipients"); } if (subject == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined subject"); } if (body == null) { throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent"); } if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) { throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType"); } String status = null; try { Properties props = new Properties(); props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host")); props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port")); Object[] params = new Object[4]; params[0] = (String) subject; params[1] = (String) fromAddress; params[2] = (String) ccRecipient; params[3] = (String) StringUtils.join(toRecipients); logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params); Session session = Session.getDefaultInstance(props); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(fromAddress)); Address[] toAddresses = new Address[toRecipients.length]; for (int i = 0; i < toAddresses.length; i++) { toAddresses[i] = new InternetAddress(toRecipients[i]); } message.addRecipients(Message.RecipientType.TO, toAddresses); if (StringUtils.isNotBlank(ccRecipient)) { Address ccAddress = new InternetAddress(ccRecipient); message.addRecipient(Message.RecipientType.CC, ccAddress); } message.setSubject(subject); message.setContent(body, messageType); Transport.send(message); } catch (AddressException e) { logger.error("sendMessage Address Exception occurred: {}", e.getMessage()); status = "sendMessage Address Exception occurred"; } catch (MessagingException e) { logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage()); status = "sendMessage Messaging Exception occurred"; } return new AsyncResult<String>(status); }
From source file:com.app.mail.DefaultMailSender.java
private Message _populatePasswordResetToken(String emailAddress, String passwordResetToken, Session session) throws Exception { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(PropertiesValues.OUTBOUND_EMAIL_ADDRESS, "Auction Alert")); message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress)); message.setSubject("Password Reset Token"); Map<String, Object> rootMap = new HashMap<>(); rootMap.put("passwordResetToken", passwordResetToken); rootMap.put("rootDomainName", PropertiesValues.ROOT_DOMAIN_NAME); String messageBody = VelocityEngineUtils.mergeTemplateIntoString(_velocityEngine, "template/password_token.vm", "UTF-8", rootMap); message.setContent(messageBody, "text/html"); return message; }
From source file:io.kodokojo.service.SmtpEmailSender.java
@Override public void send(List<String> to, List<String> cc, List<String> ci, String subject, String content, boolean htmlContent) { if (CollectionUtils.isEmpty(to)) { throw new IllegalArgumentException("to must be defined."); }/* ww w . ja va 2 s . c o m*/ if (isBlank(content)) { throw new IllegalArgumentException("content must be defined."); } Session session = Session.getDefaultInstance(properties, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); Message message = new MimeMessage(session); try { message.setFrom(from); message.setSubject(subject); InternetAddress[] toInternetAddress = convertToInternetAddress(to); message.setRecipients(Message.RecipientType.TO, toInternetAddress); if (CollectionUtils.isNotEmpty(cc)) { InternetAddress[] ccInternetAddress = convertToInternetAddress(cc); message.setRecipients(Message.RecipientType.CC, ccInternetAddress); } if (CollectionUtils.isNotEmpty(ci)) { InternetAddress[] ciInternetAddress = convertToInternetAddress(ci); message.setRecipients(Message.RecipientType.BCC, ciInternetAddress); } if (htmlContent) { message.setContent(content, "text/html"); } else { message.setText(content); } message.setHeader("X-Mailer", "Kodo Kojo mailer"); message.setSentDate(new Date()); Transport.send(message); } catch (MessagingException e) { LOGGER.error("Unable to send email to {} with subject '{}'", StringUtils.join(to, ","), subject, e); } }
From source file:org.apache.roller.planet.util.MailUtil.java
/** * This method is used to send a Message with a pre-defined * mime-type.//from w w w. j a v a 2 s . c o m * * @param from e-mail address of sender * @param to e-mail address(es) of recipients * @param subject subject of e-mail * @param content the body of the e-mail * @param mimeType type of message, i.e. text/plain or text/html * @throws MessagingException the exception to indicate failure */ public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc, String subject, String content, String mimeType) throws MessagingException { Message message = new MimeMessage(session); // n.b. any default from address is expected to be determined by caller. if (!StringUtils.isEmpty(from)) { InternetAddress sentFrom = new InternetAddress(from); message.setFrom(sentFrom); if (mLogger.isDebugEnabled()) mLogger.debug("e-mail from: " + sentFrom); } if (to != null) { InternetAddress[] sendTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress(to[i]); if (mLogger.isDebugEnabled()) mLogger.debug("sending e-mail to: " + to[i]); } message.setRecipients(Message.RecipientType.TO, sendTo); } if (cc != null) { InternetAddress[] copyTo = new InternetAddress[cc.length]; for (int i = 0; i < cc.length; i++) { copyTo[i] = new InternetAddress(cc[i]); if (mLogger.isDebugEnabled()) mLogger.debug("copying e-mail to: " + cc[i]); } message.setRecipients(Message.RecipientType.CC, copyTo); } if (bcc != null) { InternetAddress[] copyTo = new InternetAddress[bcc.length]; for (int i = 0; i < bcc.length; i++) { copyTo[i] = new InternetAddress(bcc[i]); if (mLogger.isDebugEnabled()) mLogger.debug("blind copying e-mail to: " + bcc[i]); } message.setRecipients(Message.RecipientType.BCC, copyTo); } message.setSubject((subject == null) ? "(no subject)" : subject); message.setContent(content, mimeType); message.setSentDate(new java.util.Date()); // First collect all the addresses together. Address[] remainingAddresses = message.getAllRecipients(); int nAddresses = remainingAddresses.length; boolean bFailedToSome = false; SendFailedException sendex = new SendFailedException("Unable to send message to some recipients"); // Try to send while there remain some potentially good addresses do { // Avoid a loop if we are stuck nAddresses = remainingAddresses.length; try { // Send to the list of remaining addresses, ignoring the addresses attached to the message Transport.send(message, remainingAddresses); } catch (SendFailedException ex) { bFailedToSome = true; sendex.setNextException(ex); // Extract the remaining potentially good addresses remainingAddresses = ex.getValidUnsentAddresses(); } } while (remainingAddresses != null && remainingAddresses.length > 0 && remainingAddresses.length != nAddresses); if (bFailedToSome) throw sendex; }
From source file:com.sun.socialsite.util.MailUtil.java
/** * This method is used to send a Message with a pre-defined * mime-type.//from ww w .j ava2 s.co m * * @param from e-mail address of sender * @param to e-mail address(es) of recipients * @param subject subject of e-mail * @param content the body of the e-mail * @param mimeType type of message, i.e. text/plain or text/html * @throws MessagingException the exception to indicate failure */ public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc, String subject, String content, String mimeType) throws MessagingException { Message message = new MimeMessage(session); // n.b. any default from address is expected to be determined by caller. if (!StringUtils.isEmpty(from)) { InternetAddress sentFrom = new InternetAddress(from); message.setFrom(sentFrom); if (mLogger.isDebugEnabled()) mLogger.debug("e-mail from: " + sentFrom); } if (to != null) { InternetAddress[] sendTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress(to[i]); if (mLogger.isDebugEnabled()) mLogger.debug("sending e-mail to: " + to[i]); } message.setRecipients(Message.RecipientType.TO, sendTo); } if (cc != null) { InternetAddress[] copyTo = new InternetAddress[cc.length]; for (int i = 0; i < cc.length; i++) { copyTo[i] = new InternetAddress(cc[i]); if (mLogger.isDebugEnabled()) mLogger.debug("copying e-mail to: " + cc[i]); } message.setRecipients(Message.RecipientType.CC, copyTo); } if (bcc != null) { InternetAddress[] copyTo = new InternetAddress[bcc.length]; for (int i = 0; i < bcc.length; i++) { copyTo[i] = new InternetAddress(bcc[i]); if (mLogger.isDebugEnabled()) mLogger.debug("blind copying e-mail to: " + bcc[i]); } message.setRecipients(Message.RecipientType.BCC, copyTo); } message.setSubject((subject == null) ? "(no subject)" : subject); message.setContent(content, mimeType); message.setSentDate(new java.util.Date()); // First collect all the addresses together. Address[] remainingAddresses = message.getAllRecipients(); int nAddresses = remainingAddresses.length; boolean bFailedToSome = false; SendFailedException sendex = new SendFailedException("Unable to send message to some recipients"); // Try to send while there remain some potentially good addresses do { // Avoid a loop if we are stuck nAddresses = remainingAddresses.length; try { // Send to the list of remaining addresses, ignoring the addresses attached to the message Startup.getMailProvider().getTransport().sendMessage(message, remainingAddresses); } catch (SendFailedException ex) { bFailedToSome = true; sendex.setNextException(ex); // Extract the remaining potentially good addresses remainingAddresses = ex.getValidUnsentAddresses(); } } while (remainingAddresses != null && remainingAddresses.length > 0 && remainingAddresses.length != nAddresses); if (bFailedToSome) throw sendex; }
From source file:org.collectionspace.chain.csp.persistence.file.TestGeneral.java
/** * Sets up and sends email message providing you have set up the email address to send to *//*from w ww. ja v a 2 s. c om*/ @Test public void testEmail() { Boolean doIreallyWantToSpam = false; // set to true when you have configured the email addresses /* please personalises these emails before sending - I don't want your spam. */ String from = "admin@collectionspace.org"; String[] recipients = { "" }; String SMTP_HOST_NAME = "localhost"; String SMTP_PORT = "25"; String message = "Hi, Test Message Contents"; String subject = "A test from collectionspace test suite"; String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //REM - Replace. This is pre-JDK 1.4 code, from the days when JSSE was a separate download. Fix the imports so they refer to the classes in javax.net.ssl If you really want to get hold of a specific instance, you can use Security.getProvider(name). You'll find the appropriate names in the providers documentation. boolean debug = true; Properties props = new Properties(); props.put("mail.smtp.host", SMTP_HOST_NAME); //props.put("mail.smtp.auth", "true"); props.put("mail.smtp.auth", "false"); props.put("mail.debug", "true"); props.put("mail.smtp.port", SMTP_PORT); props.put("mail.smtp.socketFactory.port", SMTP_PORT); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); Session session = Session.getDefaultInstance(props); session.setDebug(debug); if (doIreallyWantToSpam) { Message msg = new MimeMessage(session); InternetAddress addressFrom; try { addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type msg.setSubject(subject); msg.setContent(message, "text/plain"); if (doIreallyWantToSpam) { Transport.send(msg); assertTrue(doIreallyWantToSpam); } } catch (AddressException e) { log.debug(e.getMessage()); assertTrue(false); } catch (MessagingException e) { log.debug(e.getMessage()); assertTrue(false); } } //assertTrue(doIreallyWantToSpam); }