List of usage examples for javax.mail.internet MimeMessage setRecipients
public void setRecipients(Message.RecipientType type, String addresses) throws MessagingException
From source file:edu.washington.iam.tools.IamMailSender.java
public void sendWithOwnerCc(IamMailMessage msg, DNSVerifier verifier, List<String> cns) { MimeMessage mime = genMimeMessage(msg); try {//from w w w. jav a2s . co m List<String> owners = new Vector(); for (int i = 0; i < cns.size(); i++) verifier.isOwner(cns.get(i), null, owners); Address[] oAddrs = new Address[owners.size()]; for (int i = 0; i < owners.size(); i++) { oAddrs[i] = new InternetAddress(owners.get(i) + "@uw.edu"); // log.debug(" cc to: " + owners.get(i)); } mime.setRecipients(RecipientType.CC, oAddrs); mailSender.send(mime); } catch (DNSVerifyException ex) { log.error("checking dns: " + ex.getMessage()); } catch (MessagingException e) { log.error("iam mail failure: " + e); } }
From source file:org.nuxeo.ecm.platform.ec.notification.email.EmailHelper.java
protected void sendmail0(Map<String, Object> mail) throws MessagingException, IOException, TemplateException, LoginException, RenderingException { Session session = getSession();/*from w w w . j av a 2 s.co m*/ if (javaMailNotAvailable || session == null) { log.warn("Not sending email since JavaMail is not configured"); return; } // Construct a MimeMessage MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(session.getProperty("mail.from"))); Object to = mail.get("mail.to"); if (!(to instanceof String)) { log.error("Invalid email recipient: " + to); return; } msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse((String) to, false)); RenderingService rs = Framework.getService(RenderingService.class); DocumentRenderingContext context = new DocumentRenderingContext(); context.remove("doc"); context.putAll(mail); context.setDocument((DocumentModel) mail.get("document")); context.put("Runtime", Framework.getRuntime()); String customSubjectTemplate = (String) mail.get(NotificationConstants.SUBJECT_TEMPLATE_KEY); if (customSubjectTemplate == null) { String subjTemplate = (String) mail.get(NotificationConstants.SUBJECT_KEY); Template templ = new Template("name", new StringReader(subjTemplate), stringCfg); Writer out = new StringWriter(); templ.process(mail, out); out.flush(); msg.setSubject(out.toString(), "UTF-8"); } else { rs.registerEngine(new NotificationsRenderingEngine(customSubjectTemplate)); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String subjectMail = "<HTML><P>No parsing Succeded !!!</P></HTML>"; for (RenderingResult result : results) { subjectMail = (String) result.getOutcome(); } subjectMail = NotificationServiceHelper.getNotificationService().getEMailSubjectPrefix() + subjectMail; msg.setSubject(subjectMail, "UTF-8"); lc.logout(); } msg.setSentDate(new Date()); rs.registerEngine(new NotificationsRenderingEngine((String) mail.get(NotificationConstants.TEMPLATE_KEY))); LoginContext lc = Framework.login(); Collection<RenderingResult> results = rs.process(context); String bodyMail = "<HTML><P>No parsing Succedeed !!!</P></HTML>"; for (RenderingResult result : results) { bodyMail = (String) result.getOutcome(); } lc.logout(); rs.unregisterEngine("ftl"); msg.setContent(bodyMail, "text/html; charset=utf-8"); // Send the message. Transport.send(msg); }
From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java
@Override public void notifyEmailUpdated(String oldAddress, String newAddress) { try {/* ww w . j a va2 s.c o m*/ //Create the message body final MimeBodyPart msg = new MimeBodyPart(); msg.setContent( "Your Business Email Address has changed\n" + "\n" + "Old Email Address: " + oldAddress + "\n" + "New Email Address: " + newAddress + "\n" + "\n" + "If you have any questions, please contact your Human Resources department.", "text/plain"); final MimeMessage message = this.javaMailSender.createMimeMessage(); final Address[] recipients; if (StringUtils.isNotEmpty(oldAddress)) { recipients = new Address[] { new InternetAddress(oldAddress), new InternetAddress(newAddress) }; } else { recipients = new Address[] { new InternetAddress(newAddress) }; } message.setRecipients(RecipientType.TO, recipients); message.setFrom(new InternetAddress("payroll@ohr.wisc.edu")); message.setSubject("Business Email Address Change"); // sign the message body if (this.smimeSignedGenerator != null) { final MimeMultipart mm = this.smimeSignedGenerator.generate(msg, "BC"); message.setContent(mm, mm.getContentType()); } // no signing keystore configured, send the message unsigned else { message.setContent(msg.getContent(), msg.getContentType()); } message.saveChanges(); this.javaMailSender.send(message); this.logger.info("Sent notification of email address change from {} to {}", oldAddress, newAddress); } catch (Exception e) { this.logger.error( "Failed to send notification email for change from " + oldAddress + " to " + newAddress, e); } }
From source file:net.fenyo.mail4hotspot.service.MailManager.java
public void sendMessage(Address from_addr, Address[] to_addr, Address[] cc_addr, String subject, String content) throws MessagingException { final MimeMessage msg = new MimeMessage(session); msg.setFrom(from_addr);/*from w w w . j ava2 s .c o m*/ msg.setRecipients(Message.RecipientType.TO, to_addr); if (cc_addr.length > 0) msg.setRecipients(Message.RecipientType.CC, cc_addr); msg.setSubject(subject, "UTF-8"); msg.setContent(content, "text/plain"); transport.sendMessage(msg, ArrayUtils.addAll(to_addr, cc_addr)); }
From source file:org.jumpmind.metl.core.runtime.flow.FlowRuntime.java
protected void sendNotifications(Notification.EventType eventType) { if (notifications != null && notifications.size() > 0) { Transport transport = null;//www . jav a2s. com Date date = new Date(); flowParameters.put("_date", DateFormatUtils.format(date, DATE_FORMAT)); flowParameters.put("_time", DateFormatUtils.format(date, TIME_FORMAT)); try { for (Notification notification : notifications) { if (notification.getEventType().equals(eventType.toString())) { log.info("Sending notification '" + notification.getName() + "' of level '" + notification.getLevel() + "' and type '" + notification.getNotifyType() + "'"); transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession.getSession()); message.setSentDate(new Date()); message.setRecipients(RecipientType.BCC, notification.getRecipients()); message.setSubject( FormatUtils.replaceTokens(notification.getSubject(), flowParameters, true)); message.setText(FormatUtils.replaceTokens(notification.getMessage(), flowParameters, true)); try { transport.sendMessage(message, message.getAllRecipients()); } catch (MessagingException e) { log.error("Failure while sending notification", e); } } } } catch (MessagingException e) { log.error("Failure while preparing notification", e); } finally { mailSession.closeTransport(transport); } } }
From source file:com.project.implementation.ReservationImplementation.java
public String makeReservation(GuestDTO guestDTO, Integer no_of_rooms_Int, Date checkin_date, Date checkout_date) {/*from w w w. j a v a 2 s . c om*/ Integer guestID = 0, guestCount; String room_selected = guestDTO.getRoom_no_selected(); Guest guestObject = new Guest(); try { org.apache.commons.beanutils.BeanUtils.copyProperties(guestObject, guestDTO); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //check email id if exist guestID = guestDAO.checkGuestExist(guestDTO.getGuest_email(), guestDTO.getLicense_no()); System.out.println("guestID: " + guestID); //if email id, license exist if (!(guestID == 0)) { System.out.println("value = "); //update details guestCount = guestDAO.updateUserDetails(guestID, guestDTO.getGuest_name(), guestDTO.getStreet(), guestDTO.getCity(), guestDTO.getState(), guestDTO.getZip()); if (guestCount != 0) guestObject = guestDAO.getGuestRecord(guestID); } else { guestObject = guestDAO.save(guestObject); } String randomDate = FastDateFormat.getInstance("dd-MM-yyyy").format(System.currentTimeMillis()); UUID id = UUID.randomUUID(); String token_no = String.valueOf(id); //System.out.println(sensor_id); // String token_no = guestObject.getLicense_no() + guestObject.getGuest_id()+randomDate; java.util.Date todayUtilDate = Calendar.getInstance().getTime();//2015-12-05 java.sql.Date todaySqlDate = new java.sql.Date(todayUtilDate.getTime()); Reservation reservationObject = new Reservation(); // reservationObject.setReservation_id(0); reservationObject.setGuest_id(guestObject.getGuest_id()); reservationObject.setReservation_token(token_no); reservationObject.setReservation_date(todaySqlDate); reservationObject.setReservation_status(ReservationStatus.R); reservationObject = reservationDAO.save(reservationObject); // Integer reservation_id = reservationObject.getReservation_id(); String[] resultStringArray = guestDTO.getRoom_no_selected().split(","); ArrayList<Integer> arrRooms = new ArrayList<Integer>(); for (String str : resultStringArray) { arrRooms.add(Integer.parseInt(str)); CheckinRoomMapping checkinRoomMappingObject = new CheckinRoomMapping(); checkinRoomMappingObject.setReservation(reservationObject); checkinRoomMappingObject.setRoom_no(Integer.parseInt(str)); checkinRoomMappingObject.setCheckin_date(checkin_date); checkinRoomMappingObject.setCheckout_date(checkout_date); checkinRoomMappingObject.setGuest_count(0); checkinRoomMappingObject.setMappingId(0); checkinRoomMappingDAO.save(checkinRoomMappingObject); } //add email code start here final String from = "express.minihotel@gmail.com"; String to = guestObject.getGuest_email(); String body = "Hello " + guestObject.getGuest_name() + ", <br/><br></br>Your reservation has been confirmed.Your reservation ID is <font color='red'><b>" + token_no + "</b></font>.</br>Please bring the Driving License for verification at the time of Check In.</br><br></br>" + "<b>Note:</b>If you want to cancel the reservation, " + "please <a href=\'http://52.53.255.195:8080/CmpE275Team07Fall2015TermProject/v1/cancelReservation?reservation_token=" + token_no + "\'>Click Here</a><br></br>--<i>Express Hotel</i>"; String subject = "Express Hotel Reservation Confirmation <" + token_no + ">"; final String password = "Minihotel@2015"; 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.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { MimeMessage email = new MimeMessage(session); email.setFrom(new InternetAddress(from)); email.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to)); email.setSubject(subject); email.setContent(body, "text/html"); Transport.send(email); } catch (MessagingException e) { throw new RuntimeException(e); } //email code end here return token_no; }
From source file:org.apache.juddi.subscription.notify.USERFRIENDLYSMTPNotifier.java
@Override public DispositionReport notifySubscriptionListener(NotifySubscriptionListener body) throws DispositionReportFaultMessage, RemoteException { try {/*from w ww . j a v a 2 s . com*/ log.info("Sending notification email to " + notificationEmailAddress + " from " + getEMailProperties().getProperty("mail.smtp.from", "jUDDI")); if (session != null && notificationEmailAddress != null) { MimeMessage message = new MimeMessage(session); InternetAddress address = new InternetAddress(notificationEmailAddress); Address[] to = { address }; message.setRecipients(RecipientType.TO, to); message.setFrom(new InternetAddress(getEMailProperties().getProperty("mail.smtp.from", "jUDDI"))); //maybe nice to use a template rather then sending raw xml. String subscriptionResultXML = JAXBMarshaller.marshallToString(body, JAXBMarshaller.PACKAGE_SUBSCR_RES); Multipart mp = new MimeMultipart(); MimeBodyPart content = new MimeBodyPart(); String msg_content = ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.body"); msg_content = String .format(msg_content, StringEscapeUtils.escapeHtml(this.publisherName), StringEscapeUtils.escapeHtml(AppConfig.getConfiguration() .getString(Property.JUDDI_NODE_ID, "(unknown node id!)")), GetSubscriptionType(body), GetChangeSummary(body)); content.setContent(msg_content, "text/html; charset=UTF-8;"); mp.addBodyPart(content); MimeBodyPart attachment = new MimeBodyPart(); attachment.setContent(subscriptionResultXML, "text/xml; charset=UTF-8;"); attachment.setFileName("uddiNotification.xml"); mp.addBodyPart(attachment); message.setContent(mp); message.setSubject(ResourceConfig.getGlobalMessage("notifications.smtp.userfriendly.subject") + " " + body.getSubscriptionResultsList().getSubscription().getSubscriptionKey()); Transport.send(message); } else { throw new DispositionReportFaultMessage("Session is null!", null); } } catch (Exception e) { log.error(e.getMessage(), e); throw new DispositionReportFaultMessage(e.getMessage(), null); } DispositionReport dr = new DispositionReport(); Result res = new Result(); dr.getResult().add(res); return dr; }
From source file:tsuboneSystem.original.manager.MailManager.java
/** * ?/*from w ww .ja va2 s .c o m*/ * @return */ public boolean sendMail() { //???TRUE if (!check()) { return false; } Properties objPrp = new Properties(); objPrp.setProperty("mail.smtp.host", "smtp.gmail.com"); objPrp.setProperty("mail.smtp.port", "465"); objPrp.setProperty("mail.smtp.auth", "true"); // objPrp.setProperty("mail.smtp.connectiontimeout", "5000"); objPrp.setProperty("mail.smtp.timeout", "5000"); //???????????JavaMail?Message-ID????? objPrp.setProperty("mail.user", "kagucho.net@gmail.com"); objPrp.setProperty("mail.host", "smtp.gmail.com"); //???????? objPrp.setProperty("mail.debug", "true"); // SSL objPrp.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); objPrp.setProperty("mail.smtp.socketFactory.fallback", "false"); objPrp.setProperty("mail.smtp.socketFactory.port", "465"); String address = ConfigUtil.getConfig("mail.address"); String pw = ConfigUtil.getConfig("mail.pw"); // Session session = Session.getInstance(objPrp, new PlainAuthenticator(address, pw)); // ?? MimeMessage objMsg = new MimeMessage(session); try { // ? objMsg.setFrom(new InternetAddress(address, displayName)); // ?? objMsg.setSubject(title, encoding); // ?TO????CCBCC? objMsg.setRecipients(Message.RecipientType.BCC, getToAddress()); // objMsg.setText(getContent(), encoding); // ? SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); try { t.connect("smtp.gmail.com", address, pw); t.sendMessage(objMsg, objMsg.getAllRecipients()); } finally { t.close(); } return false; } catch (UnsupportedEncodingException e) { e.printStackTrace(); return true; } catch (MessagingException e) { e.printStackTrace(); return true; } }
From source file:org.apache.archiva.redback.integration.mail.MailerImpl.java
public void sendMessage(Collection<String> recipients, String subject, String content) { if (recipients.isEmpty()) { log.warn("Mail Not Sent - No mail recipients for email. subject [{}]", subject); return;/*from ww w . j av a 2s . c om*/ } String fromAddress = config.getString(UserConfigurationKeys.EMAIL_FROM_ADDRESS); String fromName = config.getString(UserConfigurationKeys.EMAIL_FROM_NAME); if (StringUtils.isEmpty(fromAddress)) { fromAddress = System.getProperty("user.name") + "@localhost"; } // TODO: Allow for configurable message headers. try { MimeMessage message = javaMailSender.createMimeMessage(); message.setSubject(subject); message.setText(content); InternetAddress from = new InternetAddress(fromAddress, fromName); message.setFrom(from); List<Address> tos = new ArrayList<Address>(); for (String mailbox : recipients) { InternetAddress to = new InternetAddress(mailbox.trim()); tos.add(to); } message.setRecipients(Message.RecipientType.TO, tos.toArray(new Address[tos.size()])); log.debug("mail content {}", content); javaMailSender.send(message); } catch (AddressException e) { log.error("Unable to send message, subject [{}]", subject, e); } catch (MessagingException e) { log.error("Unable to send message, subject [{}]", subject, e); } catch (UnsupportedEncodingException e) { log.error("Unable to send message, subject [{}]", subject, e); } }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Send an email. Also sends it as a gmail if applicable, and does password checking. * @param host host of SMTP server/*from www . j av a2 s . c om*/ * @param uName username of email account * @param pWord password of email account * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email * @param toEMailAddr the email addr of who this is going to * @param subject the Textual subject line of the email * @param bodyText the body text of the email (plain text???) * @param fileAttachment and optional file to be attached to the email * @return true if the msg was sent, false if not */ public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord, final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText, final String mimeType, @SuppressWarnings("unused") final String port, @SuppressWarnings("unused") final String security, final File fileAttachment) { String userName = uName; String password = pWord; Boolean fail = false; ArrayList<String> userAndPass = new ArrayList<String>(); Properties props = System.getProperties(); props.put("mail.smtp.host", host); //$NON-NLS-1$ props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ boolean usingSSL = false; if (usingSSL) { props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } Session session = Session.getInstance(props, null); session.setDebug(instance.isDebugging); if (instance.isDebugging) { log.debug("Host: " + host); //$NON-NLS-1$ log.debug("UserName: " + userName); //$NON-NLS-1$ log.debug("Password: " + password); //$NON-NLS-1$ log.debug("From: " + fromEMailAddr); //$NON-NLS-1$ log.debug("To: " + toEMailAddr); //$NON-NLS-1$ log.debug("Subject: " + subject); //$NON-NLS-1$ } try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEMailAddr)); if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$ { StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$ InternetAddress[] address = new InternetAddress[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { String toStr = st.nextToken().trim(); address[i++] = new InternetAddress(toStr); } msg.setRecipients(Message.RecipientType.TO, address); } else { InternetAddress[] address = { new InternetAddress(toEMailAddr) }; msg.setRecipients(Message.RecipientType.TO, address); } msg.setSubject(subject); //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\""); // create the second message part if (fileAttachment != null) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\""); //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\""); MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileAttachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); } else { // add the Multipart to the message msg.setContent(bodyText, mimeType); } // set the Date: header msg.setSentDate(new Date()); // send the message int cnt = 0; do { cnt++; SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$ try { t.connect(host, userName, password); t.sendMessage(msg, msg.getAllRecipients()); fail = false; } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } //wrong username or password, get new one if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$ { fail = true; userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow()); if (userAndPass == null) {//the user is done return false; } // else //try again userName = userAndPass.get(0); password = userAndPass.get(1); } } finally { log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$ t.close(); } } while (fail && cnt < 6); } catch (MessagingException mex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); //mex.printStackTrace(); Exception ex = null; if ((ex = mex.getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } return false; } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex); ex.printStackTrace(); } if (fail) { return false; } //else return true; }