List of usage examples for javax.mail.internet MimeMessage setRecipients
public void setRecipients(Message.RecipientType type, String addresses) throws MessagingException
From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java
/** * This method performs the treatment of the technical send: * <ul>//from w ww. j av a 2s . c om * <li>connection to the SMTP server</li> * <li>sending</li> * <li>closing the connection</li> * </ul> * @param mail the original data from which the given {@link MimeMessage} has been initialized. * @param smtpConfiguration the SMTP configuration. * @param session the current mail session. * @param messageToSend the technical message to send. * @param batchedToAddresses the receivers of the message. * @throws MessagingException */ private void performSend(final MailToSend mail, final SmtpConfiguration smtpConfiguration, Session session, MimeMessage messageToSend, List<InternetAddress[]> batchedToAddresses) throws MessagingException { // Creating a Transport connection (TCP) final Transport transport; if (smtpConfiguration.isSecure()) { transport = session.getTransport(SmtpConfiguration.SECURE_TRANSPORT); } else { transport = session.getTransport(SmtpConfiguration.SIMPLE_TRANSPORT); } // Adding send reporting listener transport.addTransportListener(new SmtpMailSendReportListener(mail)); try { if (smtpConfiguration.isAuthenticate()) { transport.connect(smtpConfiguration.getServer(), smtpConfiguration.getPort(), smtpConfiguration.getUsername(), smtpConfiguration.getPassword()); } else { transport.connect(smtpConfiguration.getServer(), smtpConfiguration.getPort(), null, null); } for (InternetAddress[] toAddressBatch : batchedToAddresses) { messageToSend.setRecipients(mail.getTo().getRecipientType().getTechnicalType(), toAddressBatch); transport.sendMessage(messageToSend, toAddressBatch); } } finally { try { transport.close(); } catch (Exception e) { SilverTrace.error("mail", "SmtpMailSender.send()", "root.EX_IGNORED", "ClosingTransport", e); } } }
From source file:org.apache.james.core.builder.MimeMessageBuilder.java
public MimeMessage build() throws MessagingException { Preconditions.checkState(!(text.isPresent() && content.isPresent()), "Can not get at the same time a text and a content"); MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties())); if (text.isPresent()) { mimeMessage.setContent(text.get(), textContentType.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE)); }/*from w w w .j a va 2s . c o m*/ if (content.isPresent()) { mimeMessage.setContent(content.get()); } if (sender.isPresent()) { mimeMessage.setSender(sender.get()); } if (subject.isPresent()) { mimeMessage.setSubject(subject.get()); } ImmutableList<InternetAddress> fromAddresses = from.build(); if (!fromAddresses.isEmpty()) { mimeMessage.addFrom(fromAddresses.toArray(new InternetAddress[fromAddresses.size()])); } List<InternetAddress> toAddresses = to.build(); if (!toAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses.toArray(new InternetAddress[toAddresses.size()])); } List<InternetAddress> ccAddresses = cc.build(); if (!ccAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses.toArray(new InternetAddress[ccAddresses.size()])); } List<InternetAddress> bccAddresses = bcc.build(); if (!bccAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddresses.toArray(new InternetAddress[bccAddresses.size()])); } MimeMessage wrappedMessage = MimeMessageWrapper.wrap(mimeMessage); List<Header> headerList = headers.build(); for (Header header : headerList) { if (header.name.equals("Message-ID") || header.name.equals("Date")) { wrappedMessage.setHeader(header.name, header.value); } else { wrappedMessage.addHeader(header.name, header.value); } } wrappedMessage.saveChanges(); return wrappedMessage; }
From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java
/** * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist. * * Json sent should have following keys : * * - to : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"] * - cc : json array of email to 'CC' email ex: ["him@rm.fr"] * - bcc : json array of email to add recipient as blind CC ["secret@rm.fr"] * - subject : subject of email//w ww . j a va 2 s . c o m * - body : Body of email * * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory. * * complete json example : * * { * "to": ["you@rm.fr", "another-guy@rm.fr"], * "cc": ["him@rm.fr"], * "bcc": ["secret@rm.fr"], * "subject": "test email", * "body": "Hi, this a test EMail, please do not reply." * } * */ @RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json") @ResponseBody public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request) throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException { JSONObject payload = new JSONObject(rawRequest); InternetAddress[] to = this.populateRecipient("to", payload); InternetAddress[] cc = this.populateRecipient("cc", payload); InternetAddress[] bcc = this.populateRecipient("bcc", payload); this.checkSubject(payload); this.checkBody(payload); this.checkRecipient(to, cc, bcc); LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to=" + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc=" + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles")); LOG.debug("EMail request : " + payload.toString()); // Instanciate MimeMessage Properties props = System.getProperties(); props.put("mail.smtp.host", this.emailFactory.getSmtpHost()); props.put("mail.protocol.port", this.emailFactory.getSmtpPort()); Session session = Session.getInstance(props, null); MimeMessage message = new MimeMessage(session); // Generate From header InternetAddress from = new InternetAddress(); from.setAddress(this.georConfig.getProperty("emailProxyFromAddress")); from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setFrom(from); // Generate Reply-to header InternetAddress replyTo = new InternetAddress(); replyTo.setAddress(request.getHeader("sec-email")); replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setReplyTo(new Address[] { replyTo }); // Generate to, cc and bcc headers if (to.length > 0) message.setRecipients(Message.RecipientType.TO, to); if (cc.length > 0) message.setRecipients(Message.RecipientType.CC, cc); if (bcc.length > 0) message.setRecipients(Message.RecipientType.BCC, bcc); // Add subject and body message.setSubject(payload.getString("subject"), "UTF-8"); message.setText(payload.getString("body"), "UTF-8", "plain"); message.setSentDate(new Date()); // finally send message Transport.send(message); JSONObject res = new JSONObject(); res.put("success", true); return res.toString(); }
From source file:org.georchestra.console.ws.emails.EmailController.java
/** * Send an email based on json payload. Recipient should be present in LDAP directory or in configured whitelist. * * Json sent should have following keys : * * - to : json array of email to send email to ex: ["you@rm.fr", "another-guy@rm.fr"] * - cc : json array of email to 'CC' email ex: ["him@rm.fr"] * - bcc : json array of email to add recipient as blind CC ["secret@rm.fr"] * - subject : subject of email//from w ww .j a v a 2 s .c o m * - body : Body of email * * Either 'to', 'cc' or 'bcc' parameter must be present in request. 'subject' and 'body' are mandatory. * * complete json example : * * { * "to": ["you@rm.fr", "another-guy@rm.fr"], * "cc": ["him@rm.fr"], * "bcc": ["secret@rm.fr"], * "subject": "test email", * "body": "Hi, this a test EMail, please do not reply." * } * */ @RequestMapping(value = "/emailProxy", method = RequestMethod.POST, produces = "application/json; charset=utf-8", consumes = "application/json") @ResponseBody public String emailProxy(@RequestBody String rawRequest, HttpServletRequest request) throws JSONException, MessagingException, UnsupportedEncodingException, DataServiceException { JSONObject payload = new JSONObject(rawRequest); InternetAddress[] to = this.populateRecipient("to", payload); InternetAddress[] cc = this.populateRecipient("cc", payload); InternetAddress[] bcc = this.populateRecipient("bcc", payload); this.checkSubject(payload); this.checkBody(payload); this.checkRecipient(to, cc, bcc); LOG.info("EMail request : user=" + request.getHeader("sec-username") + " to=" + this.extractAddress("to", payload) + " cc=" + this.extractAddress("cc", payload) + " bcc=" + this.extractAddress("bcc", payload) + " roles=" + request.getHeader("sec-roles")); LOG.debug("EMail request : " + payload.toString()); // Instanciate MimeMessage final Session session = Session.getInstance(System.getProperties(), null); session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost()); session.getProperties().setProperty("mail.smtp.port", (new Integer(this.emailFactory.getSmtpPort())).toString()); MimeMessage message = new MimeMessage(session); // Generate From header InternetAddress from = new InternetAddress(); from.setAddress(this.georConfig.getProperty("emailProxyFromAddress")); from.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setFrom(from); // Generate Reply-to header InternetAddress replyTo = new InternetAddress(); replyTo.setAddress(request.getHeader("sec-email")); replyTo.setPersonal(request.getHeader("sec-firstname") + " " + request.getHeader("sec-lastname")); message.setReplyTo(new Address[] { replyTo }); // Generate to, cc and bcc headers if (to.length > 0) message.setRecipients(Message.RecipientType.TO, to); if (cc.length > 0) message.setRecipients(Message.RecipientType.CC, cc); if (bcc.length > 0) message.setRecipients(Message.RecipientType.BCC, bcc); // Add subject and body message.setSubject(payload.getString("subject"), "UTF-8"); message.setText(payload.getString("body"), "UTF-8", "plain"); message.setSentDate(new Date()); // finally send message Transport.send(message); JSONObject res = new JSONObject(); res.put("success", true); return res.toString(); }
From source file:bean.RedSocial.java
/** * /* w ww .j a v a 2 s. c o m*/ * @param _username * @param _email * @param _password */ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class) public void solicitarAcceso(String _username, String _email, String _password) { if (daoUsuario.obtenerUsuario(_username) != null) { throw new exceptionsBusiness.UsernameNoDisponible(); } String hash = BCrypt.hashpw(_password, BCrypt.gensalt()); Token token = new Token(_username, _email, hash); daoToken.guardarToken(token); //enviar token de acceso a la direccion email String correoEnvia = "skala2climbing@gmail.com"; String claveCorreo = "vNspLa5H"; // La configuracin para enviar correo Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.user", correoEnvia); properties.put("mail.password", claveCorreo); // Obtener la sesion Session session = Session.getInstance(properties, null); try { // Crear el cuerpo del mensaje MimeMessage mimeMessage = new MimeMessage(session); // Agregar quien enva el correo mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing")); // Los destinatarios InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) }; // Agregar los destinatarios al mensaje mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses); // Agregar el asunto al correo mimeMessage.setSubject("Confirmacin de registro"); // Creo la parte del mensaje MimeBodyPart mimeBodyPart = new MimeBodyPart(); String ip = "90.165.24.228"; mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token=" + token.getToken()); //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible"); // Crear el multipart para agregar la parte del mensaje anterior Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); // Agregar el multipart al cuerpo del mensaje mimeMessage.setContent(multipart); // Enviar el mensaje Transport transport = session.getTransport("smtp"); transport.connect(correoEnvia, claveCorreo); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (UnsupportedEncodingException | MessagingException ex) { throw new ErrorEnvioEmail(); } }
From source file:org.opens.kbaccess.controller.utils.AMailerController.java
/** * Send a mail to the specified recipients. * //from www. j a v a 2 s. co m * @param subject The mail's subject * @param message The mail's body * @param recipients The adressee * @return true if the send succeed, * false otherwise */ public boolean sendMail(String subject, String message, String[] recipients) { Session session; MimeMessage mimeMessage; Properties properties; // sanity check if (recipients.length == 0) { return true; } // set-up session properties = new Properties(); properties.put("mail.smtp.host", mailingServiceProperties.getSmtpHost()); session = Session.getDefaultInstance(properties); //session.setDebug(true); try { Address from; Address[] to = new InternetAddress[recipients.length]; // set sender from = new InternetAddress(mailingServiceProperties.getDefaultReturnAddress()); // initialize recipients list for (int i = 0; i < to.length; ++i) { to[i] = new InternetAddress(recipients[i]); } // create message mimeMessage = new MimeMessage(session); mimeMessage.setSender(from); mimeMessage.setFrom(from); mimeMessage.setReplyTo(new Address[] { from }); mimeMessage.setRecipients(Message.RecipientType.TO, to); mimeMessage.setSubject(subject); mimeMessage.setText(message, "utf-8"); // send it Transport.send(mimeMessage); } catch (MessagingException ex) { LogFactory.getLog(GuestController.class).error("Unable to send email", ex); return false; } return true; }
From source file:edu.harvard.iq.dataverse.MailServiceBean.java
public boolean sendSystemEmail(String to, String subject, String messageText) { boolean sent = false; String rootDataverseName = dataverseService.findRootDataverse().getName(); String body = messageText + BundleUtil.getStringFromBundle("notification.email.closing", Arrays.asList(BrandingUtil.getInstallationBrandName(rootDataverseName))); logger.fine("Sending email to " + to + ". Subject: <<<" + subject + ">>>. Body: " + body); try {/* ww w . java 2 s .co m*/ MimeMessage msg = new MimeMessage(session); InternetAddress systemAddress = getSystemAddress(); if (systemAddress != null) { msg.setFrom(systemAddress); msg.setSentDate(new Date()); String[] recipientStrings = to.split(","); InternetAddress[] recipients = new InternetAddress[recipientStrings.length]; for (int i = 0; i < recipients.length; i++) { try { recipients[i] = new InternetAddress('"' + recipientStrings[i] + '"', "", charset); } catch (UnsupportedEncodingException ex) { logger.severe(ex.getMessage()); } } msg.setRecipients(Message.RecipientType.TO, recipients); msg.setSubject(subject, charset); msg.setText(body, charset); try { Transport.send(msg, recipients); sent = true; } catch (SMTPSendFailedException ssfe) { logger.warning("Failed to send mail to " + to + " (SMTPSendFailedException)"); } } else { logger.fine("Skipping sending mail to " + to + ", because the \"no-reply\" address not set (" + Key.SystemEmail + " setting)."); } } catch (AddressException ae) { logger.warning("Failed to send mail to " + to); ae.printStackTrace(System.out); } catch (MessagingException me) { logger.warning("Failed to send mail to " + to); me.printStackTrace(System.out); } return sent; }
From source file:com.zimbra.cs.mime.Mime.java
/** * Remove all email addresses in rcpts from To/Cc/Bcc headers of a * MimeMessage./*w ww . j av a 2 s. c om*/ * @param mm * @param rcpts * @throws MessagingException */ public static void removeRecipients(MimeMessage mm, String[] rcpts) throws MessagingException { for (RecipientType rcptType : sRcptTypes) { Address[] addrs = mm.getRecipients(rcptType); if (addrs == null) continue; ArrayList<InternetAddress> list = new ArrayList<InternetAddress>(addrs.length); for (int j = 0; j < addrs.length; j++) { InternetAddress inetAddr = (InternetAddress) addrs[j]; String addr = inetAddr.getAddress(); boolean match = false; for (int k = 0; k < rcpts.length; k++) if (addr.equalsIgnoreCase(rcpts[k])) match = true; if (!match) list.add(inetAddr); } if (list.size() < addrs.length) { InternetAddress[] newRcpts = new InternetAddress[list.size()]; list.toArray(newRcpts); mm.setRecipients(rcptType, newRcpts); } } }
From source file:org.agnitas.util.AgnUtils.java
/** * Sends an email in the correspondent type. *//*w ww . ja va 2 s . c o m*/ public static boolean sendEmail(String from_adr, String to_adrList, String cc_adrList, String subject, String body_text, String body_html, int mailtype, String charset) { try { // create some properties and get the default Session Properties props = new Properties(); props.put("system.mail.host", getSmtpMailRelayHostname()); Session session = Session.getDefaultInstance(props, null); // session.setDebug(debug); // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from_adr)); msg.setSubject(subject, charset); msg.setSentDate(new Date()); // Set to-recipient email addresses InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList); if (toAddresses != null && toAddresses.length > 0) { msg.setRecipients(Message.RecipientType.TO, toAddresses); } // Set cc-recipient email addresses InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList); if (ccAddresses != null && ccAddresses.length > 0) { msg.setRecipients(Message.RecipientType.CC, ccAddresses); } switch (mailtype) { case 0: msg.setText(body_text, charset); break; case 1: Multipart mp = new MimeMultipart("alternative"); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(body_text, charset); mp.addBodyPart(mbp); mbp = new MimeBodyPart(); mbp.setContent(body_html, "text/html; charset=" + charset); mp.addBodyPart(mbp); msg.setContent(mp); break; } Transport.send(msg); } catch (Exception e) { logger.error("sendEmail: " + e); logger.error(AgnUtils.getStackTrace(e)); return false; } return true; }
From source file:org.openehealth.coms.cc.web_frontend.consentcreator.service.Shipper.java
/** * Sends an email to the given id including a link to the password page. The * link contains the refID./*from ww w . ja v a 2s. c o m*/ * * @param emailType * - refers to the email that shall be sent, 0 sends an email for * newly registered users, 1 sends a standard password-reset * email * @param emailaddress * @param refID * @return */ public boolean sendPasswordLinkToEmail(int emailType, User user, String refID) { String salutation = ""; if (user.getGender().equalsIgnoreCase("male")) { salutation = "geehrter Herr " + user.getName(); } else { salutation = "geehrte Frau " + user.getName(); } MailAuthenticator auth = new MailAuthenticator(emailProperties.getProperty("mail.user"), emailProperties.getProperty("mail.user.password")); // Login Properties props = (Properties) emailProperties.clone(); props.remove("mail.user"); props.remove("mail.user.password"); Session session = Session.getInstance(props, auth); String htmlContent = emailBody; htmlContent = htmlContent.replaceFirst("TITLE", emailProperties.getProperty("mail.skeleton.type." + emailType + ".title")); htmlContent = htmlContent.replaceFirst("MESSAGESUBJECT", emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject")); htmlContent = htmlContent.replaceFirst("HEADER1", emailProperties.getProperty("mail.skeleton.type." + emailType + ".header1")); htmlContent = htmlContent.replaceFirst("MESSAGE", emailProperties.getProperty("mail.skeleton.type." + emailType + ".message")); htmlContent = htmlContent.replaceFirst("SALUTATION", salutation); htmlContent = htmlContent.replaceFirst("TOPLEVELDOMAIN", emailProperties.getProperty("mail.service.domain")); htmlContent = htmlContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name")); htmlContent = htmlContent.replaceFirst("REFERER", refID); htmlContent = htmlContent.replaceFirst("BCKRGIMAGE", "'cid:header-image'"); htmlContent = htmlContent.replaceFirst("DASH", "'cid:dash'"); String textContent = emailProperties.getProperty("mail.skeleton.type." + emailType + ".title") + " - " + emailProperties.getProperty("mail.skeleton.type." + emailType + ".messagesubject") + "\n \n" + emailProperties.getProperty("mail.skeleton.type." + emailType + ".message"); textContent = textContent.replaceFirst("TOPLEVELDOMAIN", emailProperties.getProperty("mail.service.domain")); textContent = textContent.replaceFirst("SERVICENAME", emailProperties.getProperty("mail.service.name")); textContent = textContent.replaceFirst("REFERER", refID); textContent = textContent.replaceFirst("SALUTATION", salutation); textContent = textContent.replaceAll("<br>", "\n"); try { MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(emailProperties.getProperty("mail.user"))); msg.setRecipients(javax.mail.Message.RecipientType.TO, user.getEmailaddress()); msg.setSentDate(new Date()); msg.setSubject(emailProperties.getProperty("mail.skeleton.type." + emailType + ".subject")); Multipart mp = new MimeMultipart("alternative"); // plaintext MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(textContent); mp.addBodyPart(textPart); // html MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent, "text/html; charset=UTF-8"); mp.addBodyPart(htmlPart); MimeBodyPart imagePart = new MimeBodyPart(); DataSource fds = null; try { fds = new FileDataSource( new File(new URL((String) emailProperties.get("mail.image.headerbackground")).getFile())); } catch (MalformedURLException e) { Logger.getLogger(this.getClass()).error(e); } imagePart.setDataHandler(new DataHandler(fds)); imagePart.setHeader("Content-ID", "header-image"); mp.addBodyPart(imagePart); MimeBodyPart imagePart2 = new MimeBodyPart(); DataSource fds2 = null; try { fds2 = new FileDataSource( new File(new URL((String) emailProperties.get("mail.image.dash")).getFile())); } catch (MalformedURLException e) { Logger.getLogger(this.getClass()).error(e); } imagePart2.setDataHandler(new DataHandler(fds2)); imagePart2.setHeader("Content-ID", "dash"); mp.addBodyPart(imagePart2); msg.setContent(mp); Transport.send(msg); } catch (Exception e) { Logger.getLogger(this.getClass()).error(e); return false; } return true; }