List of usage examples for javax.mail Message getAllRecipients
public Address[] getAllRecipients() throws MessagingException
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Send the message using SMTP, if the configuration uses authenticated SMTP, it uses * the user stored in session to get the given login and password. * /*from w w w . j a v a 2 s .c o m*/ * @param user * @param session * @param message * @throws MessagingException */ protected void sendMessage(User user, Message message) throws MessagingException { Transport transport = cache.getMailTransport(useSSL); if (auth) { logger.debug("Use auth for smtp connection"); transport.connect(address, port, user.getName(), user.getPassword()); } else { transport.connect(address, port, null, null); } Address[] recips = message.getAllRecipients(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < recips.length; i++) { sb.append(recips[i]); if (i != recips.length - 1) { sb.append(", "); } } logger.info("Send message from " + message.getFrom()[0].toString() + " to " + sb.toString()); transport.sendMessage(message, recips); }
From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java
private void appendMessageData(SampleResult child, Message message) throws MessagingException, IOException { StringBuilder cdata = new StringBuilder(); cdata.append("Date: "); // $NON-NLS-1$ cdata.append(message.getSentDate());// TODO - use a different format here? cdata.append(NEW_LINE);/*from w w w . j a v a 2s .co m*/ cdata.append("To: "); // $NON-NLS-1$ Address[] recips = message.getAllRecipients(); // may be null for (int j = 0; recips != null && j < recips.length; j++) { cdata.append(recips[j].toString()); if (j < recips.length - 1) { cdata.append("; "); // $NON-NLS-1$ } } cdata.append(NEW_LINE); cdata.append("From: "); // $NON-NLS-1$ Address[] from = message.getFrom(); // may be null for (int j = 0; from != null && j < from.length; j++) { cdata.append(from[j].toString()); if (j < from.length - 1) { cdata.append("; "); // $NON-NLS-1$ } } cdata.append(NEW_LINE); cdata.append("Subject: "); // $NON-NLS-1$ cdata.append(message.getSubject()); cdata.append(NEW_LINE); cdata.append(NEW_LINE); Object content = message.getContent(); if (content instanceof MimeMultipart) { appendMultiPart(child, cdata, (MimeMultipart) content); } else if (content instanceof InputStream) { child.setResponseData(IOUtils.toByteArray((InputStream) content)); } else { cdata.append(content); child.setResponseData(cdata.toString(), child.getDataEncodingNoDefault()); } }
From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java
/** * Sends message to mailserver, waiting for delivery if using synchronous * mode./*from w w w . j ava 2 s. c o m*/ * * @param message * Message previously prepared by prepareMessage() * @throws MessagingException * when problems sending the mail arise * @throws IOException * TODO can not see how * @throws InterruptedException * when interrupted while waiting for delivery in synchronous * modus */ public void execute(Message message) throws MessagingException, IOException, InterruptedException { Transport tr = null; try { tr = session.getTransport(getProtocol()); SynchronousTransportListener listener = null; if (synchronousMode) { listener = new SynchronousTransportListener(); tr.addTransportListener(listener); } if (useAuthentication) { tr.connect(smtpServer, username, password); } else { tr.connect(); } tr.sendMessage(message, message.getAllRecipients()); if (listener != null /*synchronousMode==true*/) { listener.attend(); // listener cannot be null here } } finally { if (tr != null) { try { tr.close(); } catch (Exception e) { // NOOP } } logger.debug("transport closed"); } logger.debug("message sent"); return; }
From source file:org.apache.nifi.processors.standard.PutEmail.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) { final FlowFile flowFile = session.get(); if (flowFile == null) { return;// w ww .j ava 2s. c om } final Properties properties = this.getMailPropertiesFromFlowFile(context, flowFile); final Session mailSession = this.createMailSession(properties); final Message message = new MimeMessage(mailSession); final ComponentLog logger = getLogger(); try { message.addFrom(toInetAddresses(context, flowFile, FROM)); message.setRecipients(RecipientType.TO, toInetAddresses(context, flowFile, TO)); message.setRecipients(RecipientType.CC, toInetAddresses(context, flowFile, CC)); message.setRecipients(RecipientType.BCC, toInetAddresses(context, flowFile, BCC)); message.setHeader("X-Mailer", context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions(flowFile).getValue()); message.setSubject(context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue()); String messageText = context.getProperty(MESSAGE).evaluateAttributeExpressions(flowFile).getValue(); if (context.getProperty(INCLUDE_ALL_ATTRIBUTES).asBoolean()) { messageText = formatAttributes(flowFile, messageText); } String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions(flowFile) .getValue(); message.setContent(messageText, contentType); message.setSentDate(new Date()); if (context.getProperty(ATTACH_FILE).asBoolean()) { final MimeBodyPart mimeText = new PreencodedMimeBodyPart("base64"); mimeText.setDataHandler(new DataHandler(new ByteArrayDataSource( Base64.encodeBase64(messageText.getBytes("UTF-8")), contentType + "; charset=\"utf-8\""))); final MimeBodyPart mimeFile = new MimeBodyPart(); session.read(flowFile, new InputStreamCallback() { @Override public void process(final InputStream stream) throws IOException { try { mimeFile.setDataHandler( new DataHandler(new ByteArrayDataSource(stream, "application/octet-stream"))); } catch (final Exception e) { throw new IOException(e); } } }); mimeFile.setFileName(flowFile.getAttribute(CoreAttributes.FILENAME.key())); MimeMultipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeText); multipart.addBodyPart(mimeFile); message.setContent(multipart); } send(message); session.getProvenanceReporter().send(flowFile, "mailto:" + message.getAllRecipients()[0].toString()); session.transfer(flowFile, REL_SUCCESS); logger.info("Sent email as a result of receiving {}", new Object[] { flowFile }); } catch (final ProcessException | MessagingException | IOException e) { context.yield(); logger.error("Failed to send email for {}: {}; routing to failure", new Object[] { flowFile, e.getMessage() }, e); session.transfer(flowFile, REL_FAILURE); } }
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 ww. ja va 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:org.apache.roller.weblogger.util.MailUtil.java
/** * This method is used to send a Message with a pre-defined * mime-type./* w ww .j av 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(String from, String[] to, String[] cc, String[] bcc, String subject, String content, String mimeType) throws MessagingException { MailProvider mailProvider = WebloggerStartup.getMailProvider(); if (mailProvider == null) { return; } Session session = mailProvider.getSession(); 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 (log.isDebugEnabled()) log.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 (log.isDebugEnabled()) log.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 (log.isDebugEnabled()) log.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 (log.isDebugEnabled()) log.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"); Transport transport = mailProvider.getTransport(); // Try to send while there remain some potentially good addresses try { 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.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); } finally { transport.close(); } if (bFailedToSome) throw sendex; }
From source file:org.artifactory.mail.MailServiceImpl.java
/** * Send an e-mail message/* ww w . j av a 2 s . com*/ * * @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.blue.star.plugins.send_mail.java
public boolean execute_check() { Properties props = System.getProperties(); props.put("mail.smtp.host", smtpServer); if (smtpAuth) { props.put("mail.smtp.auth", "true"); }//from w w w.j a v a 2 s. co m Session session = Session.getInstance(props, null); SMTPTransport transport = null; // if (debug) // session.setDebug(true); // construct the message try { Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (subject != null) msg.setSubject(subject); msg.setHeader("X-Mailer", "blue-send-mail"); msg.setSentDate(new Date()); msg.setText(message.replace("\\n", "\n").replace("\\t", "\t")); transport = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp"); if (smtpAuth) transport.connect(smtpServer, smtpUser, smtpPass); else transport.connect(); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (MessagingException mE) { mE.printStackTrace(); this.state = common_h.STATE_CRITICAL; this.text = mE.getMessage(); return false; } finally { try { transport.close(); } catch (Exception e) { } } state = common_h.STATE_OK; text = "Message Sent!"; return true; }
From source file:org.bml.util.mail.MailUtils.java
/** * Simple mail utility/*from w w w. ja v a 2s .co m*/ * @param sendToAdresses email addresses to send the mail to * @param emailSubjectLine the subject of the email. * @param emailBody The body of the mail * @param smtpHost the smtp host * @param sender the mail address that is the sender * @param smtpPassword the password for the sender * @param smtpPort the port to contact the smtp server on * @return boolean true on success and false on error */ public static boolean sendMail(final String[] sendToAdresses, final String emailSubjectLine, final String emailBody, final String smtpHost, String sender, String smtpPassword, final int smtpPort) { if ((sendToAdresses == null) || (sendToAdresses.length == 0)) { return false; } if ((emailSubjectLine == null) || (emailBody == null)) { return false; } try { Address[] addresses = new Address[sendToAdresses.length]; for (int i = 0; i < sendToAdresses.length; i++) { addresses[i] = new InternetAddress(sendToAdresses[i]); } Properties props = System.getProperties(); props.setProperty("mail.smtp.host", smtpHost); props.setProperty("mail.smtp.localhost", smtpHost); props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.smtp.port", String.valueOf(smtpPort)); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getDefaultInstance(props, null); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); message.setRecipients(Message.RecipientType.TO, addresses); message.setSubject(emailSubjectLine); message.setContent(emailBody, "text/plain"); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(smtpHost, sender, smtpPassword); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (Throwable t) { if (LOG.isErrorEnabled()) { LOG.error("Error occured while sending mail.", t); } return false; } return true; }
From source file:org.codice.ddf.platform.email.impl.SmtpClientImpl.java
@Override public Future<Void> send(Message message) { notNull(message, "message must be non-null"); return executorService.submit(() -> { try {/*from w w w. jav a2 s . c o m*/ Transport.send(message); } catch (MessagingException e) { LOGGER.debug("Could not send message {}", message, e); return null; } SecurityLogger.audit("Sent an email: recipient={} subject={}", Arrays.toString(message.getAllRecipients()), message.getSubject()); return null; }); }