List of usage examples for javax.mail Message addRecipients
public abstract void addRecipients(RecipientType type, Address[] addresses) throws MessagingException;
From source file:com.threewks.thundr.mail.JavaMailMailer.java
private void addRecipients(Map<String, String> to, Message message, RecipientType recipientType) throws MessagingException { if (Expressive.isNotEmpty(to)) { List<Address> addresses = new ArrayList<>(); for (Entry<String, String> recipient : to.entrySet()) { addresses.add(emailAddress(recipient)); }//w w w . jav a 2 s. c o m message.addRecipients(recipientType, addresses.toArray(new Address[0])); } }
From source file:bioLockJ.module.agent.MailAgent.java
private Message getMimeMessage() throws Exception { final Message message = new MimeMessage(getSession()); message.setFrom(new InternetAddress(emailFrom)); message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getRecipients())); message.setSubject("BioLockJ " + Config.requireString(Config.PROJECT_NAME) + " " + status); message.setContent(getContent());//from ww w . jav a2 s.com return message; }
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.j ava 2 s. c om*/ * @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.liferay.mail.imap.IMAPAccessor.java
protected Message createMessage(String personalName, String sender, Address[] to, Address[] cc, Address[] bcc, String subject, String body, List<MailFile> mailFiles) throws MessagingException, UnsupportedEncodingException { Message jxMessage = new MimeMessage(_imapConnection.getSession()); jxMessage.setFrom(new InternetAddress(sender, personalName)); jxMessage.addRecipients(Message.RecipientType.TO, to); jxMessage.addRecipients(Message.RecipientType.CC, cc); jxMessage.addRecipients(Message.RecipientType.BCC, bcc); jxMessage.setSentDate(new Date()); jxMessage.setSubject(subject);// w w w . j a va 2 s .c o m MimeMultipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(body, ContentTypes.TEXT_HTML_UTF8); multipart.addBodyPart(messageBodyPart); if (mailFiles != null) { for (MailFile mailFile : mailFiles) { File file = mailFile.getFile(); if (!file.exists()) { continue; } DataSource dataSource = new FileDataSource(file); BodyPart attachmentBodyPart = new MimeBodyPart(); attachmentBodyPart.setDataHandler(new DataHandler(dataSource)); attachmentBodyPart.setFileName(mailFile.getFileName()); multipart.addBodyPart(attachmentBodyPart); } } jxMessage.setContent(multipart); return jxMessage; }
From source file:org.artifactory.mail.MailServiceImpl.java
/** * Send an e-mail message//w w w . j a va2 s . co m * * @param recipients Recipients of the message that will be sent * @param subject The subject of the message * @param body The body of the message * @param config A mail server configuration to use * @throws Exception */ @Override public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config) throws EmailException { verifyParameters(recipients, config); if (!config.isEnabled()) { log.debug("Ignoring requested mail delivery. The given configuration is disabled."); return; } boolean debugEnabled = log.isDebugEnabled(); Properties properties = new Properties(); properties.put("mail.smtp.host", config.getHost()); properties.put("mail.smtp.port", Integer.toString(config.getPort())); properties.put("mail.smtp.quitwait", "false"); //Default protocol String protocol = "smtp"; //Enable TLS if set if (config.isUseTls()) { properties.put("mail.smtp.starttls.enable", "true"); } //Enable SSL if set boolean useSsl = config.isUseSsl(); if (useSsl) { properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort())); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.socketFactory.fallback", "false"); //Requires special protocol protocol = "smtps"; } //Set debug property if enabled by the logger properties.put("mail.debug", debugEnabled); Authenticator authenticator = null; if (!StringUtils.isEmpty(config.getUsername())) { properties.put("mail.smtp.auth", "true"); authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(config.getUsername(), config.getPassword()); } }; } Session session = Session.getInstance(properties, authenticator); Message message = new MimeMessage(session); String subjectPrefix = config.getSubjectPrefix(); String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject; try { message.setSubject(fullSubject); if (!StringUtils.isEmpty(config.getFrom())) { InternetAddress addressFrom = new InternetAddress(config.getFrom()); message.setFrom(addressFrom); } InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } message.addRecipients(Message.RecipientType.TO, addressTo); //Create multi-part message in case we want to add html support Multipart multipart = new MimeMultipart("related"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(body, "text/html"); multipart.addBodyPart(htmlPart); message.setContent(multipart); //Set debug property if enabled by the logger session.setDebug(debugEnabled); //Connect and send Transport transport = session.getTransport(protocol); if (useSsl) { transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword()); } else { transport.connect(); } transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (MessagingException e) { String em = e.getMessage(); throw new EmailException( "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n", e); } }
From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java
protected void fillRecipients(AddressTemplate addressTemplate, Message email, Message.RecipientType recipientType, WorkItem workItem, JCRSessionWrapper session) throws Exception { // resolve and parse addresses String addresses = addressTemplate.getAddresses(); if (addresses != null) { addresses = evaluateExpression(workItem, addresses, session); // non-strict parsing applies to a list of mail addresses entered by a human email.addRecipients(recipientType, InternetAddress.parse(addresses, false)); }/*from w w w. j a va 2 s .co m*/ // resolve and tokenize users String userList = addressTemplate.getUsers(); if (userList != null) { String[] userIds = tokenizeActors(userList, workItem, session); List<User> users = new ArrayList<User>(); for (String userId : userIds) { if (userId.startsWith("assignableFor(")) { String task = StringUtils.substringBetween(userId, "assignableFor(", ")"); WorkflowDefinition definition = WorkflowService.getInstance() .getWorkflow("jBPM", Long.toString(workItem.getProcessInstanceId()), null) .getWorkflowDefinition(); List<JahiaPrincipal> principals = WorkflowService.getInstance().getAssignedRole(definition, task, Long.toString(workItem.getProcessInstanceId()), session); for (JahiaPrincipal principal : principals) { if (principal instanceof JahiaUser) { if (!UserPreferencesHelper.areEmailNotificationsDisabled((JahiaUser) principal)) { users.add(taskIdentityService.getUserById(((JahiaUser) principal).getUserKey())); } } else if (principal instanceof JahiaGroup) { JCRGroupNode groupNode = groupManagerService .lookupGroupByPath(principal.getLocalPath()); if (groupNode != null) { for (JCRUserNode user : groupNode.getRecursiveUserMembers()) { if (!UserPreferencesHelper.areEmailNotificationsDisabled(user)) { users.add(taskIdentityService.getUserById(user.getPath())); } } } } } } else { User userById = taskIdentityService.getUserById(userId); if (userById instanceof JBPMTaskIdentityService.UserImpl && !((JBPMTaskIdentityService.UserImpl) userById).areEmailNotificationsDisabled()) { users.add(userById); } } } email.addRecipients(recipientType, getAddresses(users)); } // resolve and tokenize groups String groupList = addressTemplate.getGroups(); if (groupList != null) { for (String groupId : tokenizeActors(groupList, workItem, session)) { org.kie.api.task.model.Group group = taskIdentityService.getGroupById(groupId); email.addRecipients(recipientType, getAddresses(group)); } } }
From source file:org.jahia.services.workflow.jbpm.JBPMMailProducer.java
private void fillRecipients(AddressTemplate addressTemplate, Message email, Message.RecipientType recipientType, Execution execution, JCRSessionWrapper session) throws MessagingException, RepositoryException, ScriptException { // resolve and parse addresses String addresses = addressTemplate.getAddresses(); if (addresses != null) { addresses = evaluateExpression(execution, addresses, session); // non-strict parsing applies to a list of mail addresses entered by a human email.addRecipients(recipientType, InternetAddress.parse(addresses, false)); }//from w ww . ja v a2 s .c o m EnvironmentImpl environment = EnvironmentImpl.getCurrent(); IdentitySession identitySession = environment.get(IdentitySession.class); AddressResolver addressResolver = environment.get(AddressResolver.class); // resolve and tokenize users String userList = addressTemplate.getUsers(); if (userList != null) { String[] userIds = tokenizeActors(userList, execution, session); List<User> users = identitySession.findUsersById(userIds); email.addRecipients(recipientType, resolveAddresses(users, addressResolver)); } // resolve and tokenize groups String groupList = addressTemplate.getGroups(); if (groupList != null) { for (String groupId : tokenizeActors(groupList, execution, session)) { Group group = identitySession.findGroupById(groupId); email.addRecipients(recipientType, addressResolver.resolveAddresses(group)); } } }
From source file:org.orbeon.oxf.processor.EmailProcessor.java
public void start(PipelineContext pipelineContext) { try {/*from w ww .j a v a 2s . c om*/ final Document dataDocument = readInputAsDOM4J(pipelineContext, INPUT_DATA); final Element messageElement = dataDocument.getRootElement(); // Get system id (will likely be null if document is generated dynamically) final LocationData locationData = (LocationData) messageElement.getData(); final String dataInputSystemId = locationData.getSystemID(); // Set SMTP host final Properties properties = new Properties(); final String testSmtpHostProperty = getPropertySet().getString(EMAIL_TEST_SMTP_HOST); if (testSmtpHostProperty != null) { // Test SMTP Host from properties overrides the local configuration properties.setProperty("mail.smtp.host", testSmtpHostProperty); } else { // Try regular config parameter and property String host = messageElement.element("smtp-host").getTextTrim(); if (host != null && !host.equals("")) { // Precedence goes to the local config parameter properties.setProperty("mail.smtp.host", host); } else { // Otherwise try to use a property host = getPropertySet().getString(EMAIL_SMTP_HOST); if (host == null) host = getPropertySet().getString(EMAIL_HOST_DEPRECATED); if (host == null) throw new OXFException("Could not find SMTP host in configuration or in properties"); properties.setProperty("mail.smtp.host", host); } } // Create session final Session session; { // Get credentials final String usernameTrimmed; final String passwordTrimmed; { final Element credentials = messageElement.element("credentials"); if (credentials != null) { final Element usernameElement = credentials.element("username"); final Element passwordElement = credentials.element("password"); usernameTrimmed = (usernameElement != null) ? usernameElement.getStringValue().trim() : null; passwordTrimmed = (passwordElement != null) ? passwordElement.getStringValue().trim() : ""; } else { usernameTrimmed = null; passwordTrimmed = null; } } // Check if credentials are supplied if (StringUtils.isNotEmpty(usernameTrimmed)) { // NOTE: A blank username doesn't trigger authentication if (logger.isInfoEnabled()) logger.info("Authentication"); // Set the auth property to true properties.setProperty("mail.smtp.auth", "true"); if (logger.isInfoEnabled()) logger.info("Username: " + usernameTrimmed); // Create an authenticator final Authenticator authenticator = new SMTPAuthenticator(usernameTrimmed, passwordTrimmed); // Create session with authenticator session = Session.getInstance(properties, authenticator); } else { if (logger.isInfoEnabled()) logger.info("No Authentication"); session = Session.getInstance(properties); } } // Create message final Message message = new MimeMessage(session); // Set From message.addFrom(createAddresses(messageElement.element("from"))); // Set To String testToProperty = getPropertySet().getString(EMAIL_TEST_TO); if (testToProperty == null) testToProperty = getPropertySet().getString(EMAIL_FORCE_TO_DEPRECATED); if (testToProperty != null) { // Test To from properties overrides local configuration message.addRecipient(Message.RecipientType.TO, new InternetAddress(testToProperty)); } else { // Regular list of To elements for (final Element toElement : Dom4jUtils.elements(messageElement, "to")) { final InternetAddress[] addresses = createAddresses(toElement); message.addRecipients(Message.RecipientType.TO, addresses); } } // Set Cc for (final Element ccElement : Dom4jUtils.elements(messageElement, "cc")) { final InternetAddress[] addresses = createAddresses(ccElement); message.addRecipients(Message.RecipientType.CC, addresses); } // Set Bcc for (final Element bccElement : Dom4jUtils.elements(messageElement, "bcc")) { final InternetAddress[] addresses = createAddresses(bccElement); message.addRecipients(Message.RecipientType.BCC, addresses); } // Set headers if any for (final Element headerElement : Dom4jUtils.elements(messageElement, "header")) { final String headerName = headerElement.element("name").getTextTrim(); final String headerValue = headerElement.element("value").getTextTrim(); // NOTE: Use encodeText() in case there are non-ASCII characters message.addHeader(headerName, MimeUtility.encodeText(headerValue, DEFAULT_CHARACTER_ENCODING, null)); } // Set the email subject // The JavaMail spec is badly written and is not clear about whether this needs to be done here. But it // seems to use the platform's default charset, which we don't want to deal with. So we preemptively encode. // The result is pure ASCII so that setSubject() will not attempt to re-encode it. message.setSubject(MimeUtility.encodeText(messageElement.element("subject").getStringValue(), DEFAULT_CHARACTER_ENCODING, null)); // Handle body final Element textElement = messageElement.element("text"); final Element bodyElement = messageElement.element("body"); if (textElement != null) { // Old deprecated mechanism (simple text body) message.setText(textElement.getStringValue()); } else if (bodyElement != null) { // New mechanism with body and parts handleBody(pipelineContext, dataInputSystemId, message, bodyElement); } else { throw new OXFException("Main text or body element not found");// TODO: location info } // Send message final Transport transport = session.getTransport("smtp"); Transport.send(message); transport.close(); } catch (Exception e) { throw new OXFException(e); } }