List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:io.uengine.mail.MailAsyncService.java
@Async public void download(String type, String version, String token, String subject, String fromUser, String fromName, final String toUser, final String toName, InternetAddress[] toCC) { Session session = setMailProperties(toUser); Map model = new HashMap(); model.put("link", MessageFormatter.arrayFormat("http://www.uengine.io/download/get?type={}&version={}&token={}", new Object[] { type, version, token }).getMessage()); model.put("name", toName); String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/download.vm", "UTF-8", model);/*from w w w .jav a2 s . co m*/ try { InternetAddress from = new InternetAddress(fromUser, fromName); MimeMessage message = new MimeMessage(session); message.setFrom(from); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser)); message.setSubject(subject); message.setContent(body, "text/html; charset=utf-8"); if (toCC != null && toCC.length > 0) message.setRecipients(Message.RecipientType.CC, toCC); Transport.send(message); logger.info("{} ? ?? .", toUser); } catch (Exception e) { throw new ServiceException("?? .", e); } }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail./*from w w w.ja v a2s.c om*/ * * @param fromAddress Origin address. * @param toAddress Destination addresses. * @param subject The mail subject. * @param text The mail body. * @throws MessagingException If there is any error. */ private static MimeMessage create(String fromAddress, Collection<String> toAddress, String subject, String text, Collection<String> docsPath, List<File> tmpAttachments) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({}, {}, {}, {}, {})", new Object[] { fromAddress, toAddress, subject, text, docsPath }); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (fromAddress != null) { InternetAddress from = new InternetAddress(fromAddress); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[toAddress.size()]; int idx = 0; for (Iterator<String> it = toAddress.iterator(); it.hasNext();) { to[idx++] = new InternetAddress(it.next()); } // Build a multiparted mail with HTML and text content for better SPAM behaviour Multipart content = new MimeMultipart(); // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(text); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html;charset=UTF-8"); htmlPart.setHeader("Content-Type", "text/html;charset=UTF-8"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); idx = 0; if (docsPath != null) { for (String docPath : docsPath) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(docPath); try { final Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, false); final File tmpAttch = tmpAttachments.get(idx++); fos = new FileOutputStream(tmpAttch); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmpAttch.getPath()) { public String getContentType() { return doc.getMimeType(); } }; docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(MimeUtility.encodeText(docName)); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:eu.scape_project.pw.idp.UserManager.java
/** * Method responsible for sending a email to the user, including a link to * activate his user account.//ww w .j av a 2 s . c om * * @param user * User the activation mail should be sent to * @param serverString * Name and port of the server the user was added. * @throws CannotSendMailException * if the mail could not be sent */ public void sendActivationMail(IdpUser user, String serverString) throws CannotSendMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail())); message.setSubject("Please confirm your Planningsuite user account"); StringBuilder builder = new StringBuilder(); builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n"); builder.append("Please use the following link to confirm your Planningsuite user account: \n"); builder.append("http://" + serverString + "/idp/activateUser.jsf?uid=" + user.getActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Activation mail sent successfully to {}", user.getEmail()); } catch (Exception e) { log.error("Error at sending activation mail to {}", user.getEmail()); throw new CannotSendMailException("Error at sending activation mail to " + user.getEmail(), e); } }
From source file:it.geosolutions.geobatch.mail.SendMailAction.java
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException { final Queue<EventObject> ret = new LinkedList<EventObject>(); while (events.size() > 0) { final EventObject ev; try {// w w w. j a v a2s.c o m if ((ev = events.remove()) != null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Send Mail action.execute(): working on incoming event: " + ev.getSource()); } File mail = (File) ev.getSource(); FileInputStream fis = new FileInputStream(mail); String kmlURL = IOUtils.toString(fis); // ///////////////////////////////////////////// // Send the mail with the given KML URL // ///////////////////////////////////////////// // Recipient's email ID needs to be mentioned. String mailTo = conf.getMailToAddress(); // Sender's email ID needs to be mentioned String mailFrom = conf.getMailFromAddress(); // Get system properties Properties properties = new Properties(); // Setup mail server String mailSmtpAuth = conf.getMailSmtpAuth(); properties.put("mail.smtp.auth", mailSmtpAuth); properties.put("mail.smtp.host", conf.getMailSmtpHost()); properties.put("mail.smtp.starttls.enable", conf.getMailSmtpStarttlsEnable()); properties.put("mail.smtp.port", conf.getMailSmtpPort()); // Get the default Session object. final String mailAuthUsername = conf.getMailAuthUsername(); final String mailAuthPassword = conf.getMailAuthPassword(); Session session = Session.getDefaultInstance(properties, (mailSmtpAuth.equalsIgnoreCase("true") ? new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(mailAuthUsername, mailAuthPassword); } } : null)); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(mailFrom)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(mailTo)); // Set Subject: header field message.setSubject(conf.getMailSubject()); String mailHeaderName = conf.getMailHeaderName(); String mailHeaderValule = conf.getMailHeaderValue(); if (mailHeaderName != null && mailHeaderValule != null) { message.addHeader(mailHeaderName, mailHeaderValule); } String mailMessageText = conf.getMailContentHeader(); message.setText(mailMessageText + "\n\n" + kmlURL); // Send message Transport.send(message); if (LOGGER.isInfoEnabled()) LOGGER.info("Sent message successfully...."); } catch (MessagingException exc) { ActionExceptionHandler.handleError(conf, this, "An error occurrd when sent message ..."); continue; } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error("Send Mail action.execute(): Encountered a NULL event: SKIPPING..."); } continue; } } catch (Exception ioe) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Send Mail action.execute(): Unable to produce the output: ", ioe.getLocalizedMessage(), ioe); } throw new ActionException(this, ioe.getLocalizedMessage(), ioe); } } return ret; }
From source file:eu.scape_project.pw.idp.UserManager.java
/** * Sends the user a link to reset the password. * //from www. j a v a 2 s .c o m * @param user * the user * @param serverString * host and port of the server * @throws CannotSendMailException * if the password reset mail could not be sent */ public void sendPasswordResetMail(IdpUser user, String serverString) throws CannotSendMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail())); message.setSubject("Planningsuite password recovery"); StringBuilder builder = new StringBuilder(); builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n"); builder.append("You have requested help recovering the password for the Plato user "); builder.append(user.getUsername()).append(".\n\n"); builder.append("Please use the following link to reset your Planningsuite password: \n"); builder.append("http://" + serverString + "/idp/resetPassword.jsf?uid=" + user.getActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Sent password reset mail to " + user.getEmail()); } catch (Exception e) { log.error("Error at sending password reset mail to {}", user.getEmail()); throw new CannotSendMailException("Error at sending password reset mail to " + user.getEmail()); } }
From source file:nl.surfnet.coin.teams.control.JoinTeamController.java
private void sendJoinTeamMessage(final Team team, final Person person, final String message, final Locale locale) throws IllegalStateException, IOException { Object[] subjectValues = { team.getName() }; final String subject = messageSource.getMessage(REQUEST_MEMBERSHIP_SUBJECT, subjectValues, locale); final Set<Member> admins = grouperTeamService.findAdmins(team); if (CollectionUtils.isEmpty(admins)) { throw new RuntimeException("Team '" + team.getName() + "' has no admins to mail invites"); }/*from ww w .j av a 2 s . co m*/ final String html = composeJoinRequestMailMessage(team, person, message, locale, "html"); final String plainText = composeJoinRequestMailMessage(team, person, message, locale, "plaintext"); final List<InternetAddress> bcc = new ArrayList<InternetAddress>(); for (Member admin : admins) { try { bcc.add(new InternetAddress(admin.getEmail())); } catch (AddressException ae) { log.debug("Admin has malformed email address", ae); } } if (bcc.isEmpty()) { throw new RuntimeException( "Team '" + team.getName() + "' has no admins with valid email addresses to mail invites"); } MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { mimeMessage.addHeader("Precedence", "bulk"); mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail())); mimeMessage.setRecipients(Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()])); mimeMessage.setSubject(subject); MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html); mimeMessage.setContent(rootMixedMultipart); } }; mailService.sendAsync(preparator); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.ExceptionHandlingAction.java
private void sendEmail(String from, String subject, String body) { Properties props = new Properties(); props.put("mail.smtp.host", Objects.firstNonNull(FenixConfigurationManager.getConfiguration().getMailSmtpHost(), "localhost")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); try {//from www . j ava 2 s. com message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(CoreConfiguration.getConfiguration().defaultSupportEmailAddress())); message.setSubject(subject); message.setText(body); Transport.send(message); } catch (Exception e) { logger.error("Could not send support email! Original message was: " + body, e); } }
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 a v a 2 s .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:org.eurekastreams.server.service.actions.strategies.EmailerFactory.java
/** * Creates a "blank" email message, ready for the application to set the content (subject, body, etc.). * * @return An email message./*from ww w . j av a 2 s . com*/ * @throws MessagingException * Thrown if there are problems creating the message. */ public MimeMessage createMessage() throws MessagingException { Properties mailProps = new Properties(); mailProps.put("mail.transport.protocol", mailTransportProtocol); for (Map.Entry<String, String> cfg : transportConfiguration.entrySet()) { mailProps.put(cfg.getKey(), cfg.getValue()); } Session mailSession = Session.getInstance(mailProps, null); MimeMessage msg = new MimeMessage(mailSession); msg.setContent(new MimeMultipart("alternative")); msg.setSentDate(new Date()); msg.setFrom(new InternetAddress(defaultFromAddress)); return msg; }
From source file:org.josso.selfservices.password.EMailPasswordDistributor.java
protected void sendMail(final String mailTo, final String mailFrom, final String text) throws PasswordManagementException { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo)); mimeMessage.setFrom(new InternetAddress(mailFrom)); mimeMessage.setSubject(getMailSubject()); mimeMessage.setText(text);/*from w ww . j a va2 s . co m*/ } }; try { this.mailSender.send(preparator); } catch (MailException e) { throw new PasswordManagementException( "Cannot distribute password to [" + mailTo + "] " + e.getMessage(), e); } }