List of usage examples for javax.mail.internet MimeMessage setSubject
@Override public void setSubject(String subject) throws MessagingException
From source file:nl.surfnet.coin.teams.control.DetailTeamController.java
/** * Notifies the user that requested to join a team that his request has been * declined// w ww . j a v a 2 s . c om * * @param memberToAdd {@link Person} that wanted to join the team * @param team {@link Team} he wanted to join * @param locale {@link Locale} */ private void sendDeclineMail(final Person memberToAdd, final Team team, final Locale locale) { final String subject = messageSource.getMessage("request.mail.declined.subject", null, locale); final String html = composeDeclineMailMessage(team, locale, "html"); final String plainText = composeDeclineMailMessage(team, locale, "plaintext"); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { mimeMessage.addHeader("Precedence", "bulk"); mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail())); mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails())); mimeMessage.setSubject(subject); MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html); mimeMessage.setContent(rootMixedMultipart); } }; mailService.sendAsync(preparator); }
From source file:nl.surfnet.coin.teams.control.DetailTeamController.java
/** * Notifies the user that requested to join a team that his request has been * declined/*w w w. j a v a 2s .c om*/ * * @param memberToAdd {@link Person} that wanted to join the team * @param team {@link Team} he wanted to join * @param locale {@link Locale} */ private void sendAcceptMail(final Person memberToAdd, final Team team, final Locale locale) { final String subject = messageSource.getMessage("request.mail.accepted.subject", null, locale); final String html = composeAcceptMailMessage(team, locale, "html"); final String plainText = composeAcceptMailMessage(team, locale, "plaintext"); MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException { mimeMessage.addHeader("Precedence", "bulk"); mimeMessage.setFrom(new InternetAddress(teamEnvironment.getSystemEmail())); mimeMessage.setRecipients(Message.RecipientType.TO, convertEmailAdresses(memberToAdd.getEmails())); mimeMessage.setSubject(subject); MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html); mimeMessage.setContent(rootMixedMultipart); } }; mailService.sendAsync(preparator); }
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Create basic Message which contains all headers. No body is filled * /*from w ww .java 2 s . co m*/ * @param session the Session * @param action the action * @return message * @throws AddressException * @throws MessagingException * @throws ActionException */ protected Message createMessage(Session session, A action) throws AddressException, MessagingException { MimeMessage message = new MimeMessage(session); SMTPMessage m = action.getMessage(); message.setFrom(new InternetAddress(m.getFrom())); userPreferences.addContact(m.getTo()); userPreferences.addContact(m.getCc()); userPreferences.addContact(m.getBcc()); message.setRecipients(RecipientType.TO, MessageUtils.getRecipients(m.getTo())); message.setRecipients(RecipientType.CC, MessageUtils.getRecipients(m.getCc())); message.setRecipients(RecipientType.BCC, MessageUtils.getRecipients(m.getBcc())); message.setSubject(MessageUtils.encodeTexts(m.getSubject())); message.saveChanges(); return message; }
From source file:org.chiba.connectors.smtp.SMTPSubmissionHandler.java
private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception { URL url = new URL(uri); String recipient = url.getPath(); String server = null;/*from w w w.j av a 2 s .c o m*/ String port = null; String sender = null; String subject = null; String username = null; String password = null; StringTokenizer headers = new StringTokenizer(url.getQuery(), "&"); while (headers.hasMoreTokens()) { String token = headers.nextToken(); if (token.startsWith("server=")) { server = URLDecoder.decode(token.substring("server=".length())); continue; } if (token.startsWith("port=")) { port = URLDecoder.decode(token.substring("port=".length())); continue; } if (token.startsWith("sender=")) { sender = URLDecoder.decode(token.substring("sender=".length())); continue; } if (token.startsWith("subject=")) { subject = URLDecoder.decode(token.substring("subject=".length())); continue; } if (token.startsWith("username=")) { username = URLDecoder.decode(token.substring("username=".length())); continue; } if (token.startsWith("password=")) { password = URLDecoder.decode(token.substring("password=".length())); continue; } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("smtp server '" + server + "'"); if (username != null) { LOGGER.debug("smtp-auth username '" + username + "'"); } LOGGER.debug("mail sender '" + sender + "'"); LOGGER.debug("subject line '" + subject + "'"); } Properties properties = System.getProperties(); properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled())); properties.put("mail.smtp.from", sender); properties.put("mail.smtp.host", server); if (port != null) { properties.put("mail.smtp.port", port); } if (username != null) { properties.put("mail.smtp.auth", String.valueOf(true)); properties.put("mail.smtp.user", username); } Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password)); MimeMessage message = null; if (mediatype.startsWith("multipart/")) { message = new MimeMessage(session, new ByteArrayInputStream(data)); } else { message = new MimeMessage(session); if (mediatype.toLowerCase().indexOf("charset=") == -1) { mediatype += "; charset=\"" + encoding + "\""; } message.setText(new String(data, encoding), encoding); message.setHeader("Content-Type", mediatype); } message.setRecipient(RecipientType.TO, new InternetAddress(recipient)); message.setSubject(subject); message.setSentDate(new Date()); Transport.send(message); }
From source file:com.netflix.genie.server.jobmanager.impl.JobMonitorImpl.java
/** * Check the properties file to figure out if an email needs to be sent at * the end of the job. If yes, get mail properties and try and send email * about Job Status./*from w ww.j a v a2 s . com*/ * * @return 0 for success, -1 for failure * @throws GenieException on issue */ private boolean sendEmail(final String emailTo, final boolean killed) throws GenieException { LOG.debug("called"); final Job job = this.jobService.getJob(this.jobId); if (!this.config.getBoolean("com.netflix.genie.server.mail.enable", false)) { LOG.warn("Email is disabled but user has specified an email address."); return false; } // Sender's email ID final String fromEmail = this.config.getString("com.netflix.genie.server.mail.smpt.from", "no-reply-genie@geniehost.com"); LOG.info("From email address to use to send email: " + fromEmail); // Set the smtp server hostname. Use localhost as default final String smtpHost = this.config.getString("com.netflix.genie.server.mail.smtp.host", "localhost"); LOG.debug("Email smtp server: " + smtpHost); // Get system properties final Properties properties = new Properties(); // Setup mail server properties.setProperty("mail.smtp.host", smtpHost); // check whether authentication should be turned on Authenticator auth = null; if (this.config.getBoolean("com.netflix.genie.server.mail.smtp.auth", false)) { LOG.debug("Email Authentication Enabled"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.auth", "true"); final String userName = config.getString("com.netflix.genie.server.mail.smtp.user"); final String password = config.getString("com.netflix.genie.server.mail.smtp.password"); if (userName == null || password == null) { LOG.error("Authentication is enabled and username/password for smtp server is null"); return false; } LOG.debug("Constructing authenticator object with username" + userName + " and password " + password); auth = new SMTPAuthenticator(userName, password); } else { LOG.debug("Email authentication not enabled."); } // Get the default Session object. final Session session = Session.getInstance(properties, auth); try { // Create a default MimeMessage object. final MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(fromEmail)); // Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTo)); JobStatus jobStatus; if (killed) { jobStatus = JobStatus.KILLED; } else { jobStatus = job.getStatus(); } // Set Subject: header field message.setSubject("Genie Job " + job.getName() + " completed with Status: " + jobStatus); // Now set the actual message final String body = "Your Genie Job is complete\n\n" + "Job ID: " + job.getId() + "\n" + "Job Name: " + job.getName() + "\n" + "Status: " + job.getStatus() + "\n" + "Status Message: " + job.getStatusMsg() + "\n" + "Output Base URL: " + job.getOutputURI() + "\n"; message.setText(body); // Send message Transport.send(message); LOG.info("Sent email message successfully...."); return true; } catch (final MessagingException mex) { LOG.error("Got exception while sending email", mex); return false; } }
From source file:org.bibsonomy.util.MailUtils.java
/** * Sends a mail to the given recipients/*from www . ja va 2 s . c o m*/ * * @param recipients * @param subject * @param message * @param from * @throws MessagingException */ private void sendMail(final String[] recipients, final String subject, final String message, final String from) throws MessagingException { boolean debug = false; // create some properties and get the default Session final Session session = Session.getDefaultInstance(props, null); session.setDebug(debug); // create a message final MimeMessage msg = new MimeMessage(session); // set the from and to address final InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); final InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Optional : You can also set your custom headers in the Email if you Want //msg.addHeader("X-Sent-By", "Bibsonomy-Bot"); // Setting the Subject and Content Type msg.setSubject(subject); msg.setText(message, "UTF-8"); Transport.send(msg); }
From source file:net.naijatek.myalumni.util.mail.FreeMarkerTemplateMailerImpl.java
public void mail(final String email, final Map map, final String bodyTemplatePrefix, final String subjectTemplatePrefix) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws MessagingException, IOException { mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(email)); ////from w w w . jav a 2 s . c om // Get the subject // //BodyPart subjectPart = new MimeBodyPart(); Template subjectTextTemplate = configuration.getTemplate(subjectTemplatePrefix); final StringWriter subjectTextWriter = new StringWriter(); try { subjectTextTemplate.process(map, subjectTextWriter); } catch (TemplateException e) { throw new MailPreparationException("Can't generate Subject Text", e); } mimeMessage.setSubject(subjectTextWriter.toString()); // // Create a "text" Multipart message // Template bodyTextTemplate = configuration.getTemplate(bodyTemplatePrefix); final StringWriter bodyTextWriter = new StringWriter(); try { bodyTextTemplate.process(map, bodyTextWriter); } catch (TemplateException e) { throw new MailPreparationException("Can't generate Body Text", e); } mimeMessage.setText(bodyTextWriter.toString()); /* // @TODO - This part handles sending an attachement textPart.setDataHandler(new DataHandler(new DataSource() { public InputStream getInputStream() throws IOException { return new StringBufferInputStream(bodyTextWriter.toString()); } public OutputStream getOutputStream() throws IOException { throw new IOException("Read-only data"); } public String getContentType() { return "text/plain"; } public String getName() { return "main"; } })); mp.addBodyPart(textPart);*/ /* // Create a "HTML" Multipart message Multipart htmlContent = new MimeMultipart("related"); BodyPart htmlPage = new MimeBodyPart(); Template htmlTemplate = configuration.getTemplate(templatePrefix + "-html.ftl"); final StringWriter htmlWriter = new StringWriter(); try { htmlTemplate.process(map, htmlWriter); } catch (TemplateException e) { throw new MailPreparationException("Can't generate HTML subscription mail", e); } htmlPage.setDataHandler(new DataHandler(new DataSource() { public InputStream getInputStream() throws IOException { return new StringBufferInputStream(htmlWriter.toString()); } public OutputStream getOutputStream() throws IOException { throw new IOException("Read-only data"); } public String getContentType() { return "text/html"; } public String getName() { return "main"; } })); htmlContent.addBodyPart(htmlPage); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent); mp.addBodyPart(htmlPart); mimeMessage.setContent(mp);*/ } }; mailSender.send(preparator); }
From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java
public String send() { List attachmentList = null;/*from w w w.jav a 2 s. c om*/ AttachmentData a = null; try { Properties props = new Properties(); // Server if (smtpServer == null || smtpServer.equals("")) { log.info("samigo.email.smtpServer is not set"); smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); if (smtpServer == null || smtpServer.equals("")) { log.info("smtp@org.sakaiproject.email.api.EmailService is not set"); log.error( "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService"); return "error"; } } props.setProperty("mail.smtp.host", smtpServer); // Port if (smtpPort == null || smtpPort.equals("")) { log.warn("samigo.email.smtpPort is not set. The default port 25 will be used."); } else { props.setProperty("mail.smtp.port", smtpPort); } Session session; session = Session.getInstance(props); session.setDebug(true); MimeMessage msg = new MimeMessage(session); InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName); msg.setFrom(fromIA); InternetAddress[] toIA = { new InternetAddress(toEmailAddress, toName) }; msg.setRecipients(Message.RecipientType.TO, toIA); if ("yes".equals(ccMe)) { InternetAddress[] ccIA = { new InternetAddress(fromEmailAddress, fromName) }; msg.setRecipients(Message.RecipientType.CC, ccIA); } msg.setSubject(subject); EmailBean emailBean = (EmailBean) ContextUtil.lookupBean("email"); attachmentList = emailBean.getAttachmentList(); StringBuilder content = new StringBuilder(message); ArrayList fileList = new ArrayList(); ArrayList fileNameList = new ArrayList(); if (attachmentList != null) { if (prefixedPath == null || prefixedPath.equals("")) { log.error("samigo.email.prefixedPath is not set"); return "error"; } Iterator iter = attachmentList.iterator(); while (iter.hasNext()) { a = (AttachmentData) iter.next(); if (a.getIsLink().booleanValue()) { log.debug("send(): url"); content.append("<br/>\n\r"); content.append("<br/>"); // give a new line content.append(a.getFilename()); } else { log.debug("send(): file"); File attachedFile = getAttachedFile(a.getResourceId()); fileList.add(attachedFile); fileNameList.add(a.getFilename()); } } } Multipart multipart = new MimeMultipart(); MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content.toString(), "text/html"); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); for (int i = 0; i < fileList.size(); i++) { messageBodyPart = new MimeBodyPart(); FileDataSource source = new FileDataSource((File) fileList.get(i)); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName((String) fileNameList.get(i)); multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); Transport.send(msg); } catch (UnsupportedEncodingException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (MessagingException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (ServerOverloadException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (PermissionException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (IdUnusedException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (TypeException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } catch (IOException e) { log.error("Exception throws from send()" + e.getMessage()); return "error"; } finally { if (attachmentList != null) { if (prefixedPath != null && !prefixedPath.equals("")) { StringBuilder sbPrefixedPath; Iterator iter = attachmentList.iterator(); while (iter.hasNext()) { sbPrefixedPath = new StringBuilder(prefixedPath); sbPrefixedPath.append("/email_tmp/"); a = (AttachmentData) iter.next(); if (!a.getIsLink().booleanValue()) { deleteAttachedFile(sbPrefixedPath.append(a.getResourceId()).toString()); } } } } } return "send"; }
From source file:org.exoplatform.chat.server.ChatServer.java
public void sendMailWithAuth(String senderFullname, List<String> toList, String htmlBody, String subject) throws Exception { String host = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_HOST); String user = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_USER); String password = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PASSWORD); String port = PropertyManager.getProperty(PropertyManager.PROPERTY_MAIL_PORT); Properties props = System.getProperties(); props.put("mail.smtp.user", user); props.put("mail.smtp.password", password); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); //props.put("mail.debug", "true"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.EnableSSL.enable", "true"); Session session = Session.getInstance(props, null); //session.setDebug(true); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(user, senderFullname)); // To get the array of addresses for (String to : toList) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); }//from w w w. jav a2s .co m message.setSubject(subject); message.setContent(htmlBody, "text/html"); Transport transport = session.getTransport("smtp"); try { transport.connect(host, user, password); transport.sendMessage(message, message.getAllRecipients()); } finally { transport.close(); } }
From source file:edu.cornell.mannlib.vitro.webapp.controller.MailUsersServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { VitroRequest vreq = new VitroRequest(request); String confirmpage = "/confirmUserMail.jsp"; String errpage = "/contact_err.jsp"; String status = null; // holds the error status if (!FreemarkerEmailFactory.isConfigured(vreq)) { status = "This application has not yet been configured to send mail. " + "Email properties must be specified in the configuration properties file."; response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status); return;/*from w w w. j av a 2 s. co m*/ } String SPAM_MESSAGE = "Your message was flagged as spam."; boolean probablySpam = false; String spamReason = ""; String originalReferer = (String) request.getSession().getAttribute("commentsFormReferer"); request.getSession().removeAttribute("commentsFormReferer"); if (originalReferer == null) { originalReferer = "none"; // (the following does not support cookie-less browsing:) // probablySpam = true; // status = SPAM_MESSAGE; } else { String referer = request.getHeader("Referer"); //Review how spam works? /*if (referer.indexOf("comments")<0 && referer.indexOf("correction")<0) { probablySpam=true; status = SPAM_MESSAGE ; spamReason = "The form was not submitted from the Contact Us or Corrections page."; }*/ } String formType = vreq.getParameter("DeliveryType"); List<String> deliverToArray = null; int recipientCount = 0; String deliveryfrom = null; // get Individuals that the User mayEditAs deliverToArray = getEmailsForAllUserAccounts(vreq); //Removed all form type stuff b/c recipients pre-configured recipientCount = (deliverToArray == null) ? 0 : deliverToArray.size(); if (recipientCount == 0) { //log.error("recipientCount is 0 when DeliveryType specified as \""+formType+"\""); throw new Error("To establish the Contact Us mail capability the system administrators must " + "specify at least one email address in the current portal."); } // obtain passed in form data with a simple trim on the values String webusername = vreq.getParameter("webusername");// Null.trim(); will give you an exception String webuseremail = vreq.getParameter("webuseremail");//.trim(); String comments = vreq.getParameter("s34gfd88p9x1"); //what does this string signify? //webusername = "hjk54"; //webuseremail = "hjk54@cornell.edu"; //comments = "following are comments"; webusername = webusername.trim(); deliveryfrom = webuseremail; comments = comments.trim(); //Removed spam filtering code StringBuffer msgBuf = new StringBuffer(); // contains the intro copy for the body of the email message String lineSeparator = System.getProperty("line.separator"); // \r\n on windows, \n on unix // from MyLibrary msgBuf.setLength(0); //msgBuf.append("Content-Type: text/html; charset='us-ascii'" + lineSeparator); msgBuf.append("<html>" + lineSeparator); msgBuf.append("<head>" + lineSeparator); msgBuf.append("<style>a {text-decoration: none}</style>" + lineSeparator); msgBuf.append("<title>" + deliveryfrom + "</title>" + lineSeparator); msgBuf.append("</head>" + lineSeparator); msgBuf.append("<body>" + lineSeparator); msgBuf.append("<h4>" + deliveryfrom + "</h4>" + lineSeparator); msgBuf.append("<h4>From: " + webusername + " (" + webuseremail + ")" + " at IP address " + request.getRemoteAddr() + "</h4>" + lineSeparator); //Don't need any 'likely viewing page' portion to be emailed out to the others msgBuf.append(lineSeparator + "</i></p><h3>Comments:</h3>" + lineSeparator); if (comments == null || comments.equals("")) { msgBuf.append("<p>BLANK MESSAGE</p>"); } else { msgBuf.append("<p>" + comments + "</p>"); } msgBuf.append("</body>" + lineSeparator); msgBuf.append("</html>" + lineSeparator); String msgText = msgBuf.toString(); Calendar cal = Calendar.getInstance(); /* outFile.println("<hr/>"); outFile.println(); outFile.println("<p>"+cal.getTime()+"</p>"); outFile.println(); if (probablySpam) { outFile.println("<p>REJECTED - SPAM</p>"); outFile.println("<p>"+spamReason+"</p>"); outFile.println(); } outFile.print( msgText ); outFile.println(); outFile.println(); outFile.flush(); // outFile.close(); */ Session s = FreemarkerEmailFactory.getEmailSession(vreq); //s.setDebug(true); try { // Construct the message MimeMessage msg = new MimeMessage(s); log.debug("trying to send message from servlet"); // Set the from address msg.setFrom(new InternetAddress(webuseremail)); // Set the recipient address if (recipientCount > 0) { InternetAddress[] address = new InternetAddress[recipientCount]; for (int i = 0; i < recipientCount; i++) { address[i] = new InternetAddress(deliverToArray.get(i)); } msg.setRecipients(Message.RecipientType.TO, address); } // Set the subject and text msg.setSubject(deliveryfrom); // add the multipart to the message msg.setContent(msgText, "text/html"); // set the Date: header msg.setSentDate(new Date()); log.debug("sending from servlet"); //if (!probablySpam) Transport.send(msg); // try to send the message via smtp - catch error exceptions } catch (AddressException e) { status = "Please supply a valid email address."; log.debug("Error - status is " + status); } catch (SendFailedException e) { status = "The system was unable to deliver your mail. Please try again later. [SEND FAILED]"; log.error("Error - status is " + status); } catch (MessagingException e) { status = "The system was unable to deliver your mail. Please try again later. [MESSAGING]"; log.error("Error - status is " + status, e); } //outFile.flush(); //outFile.close(); // Redirect to the appropriate confirmation page if (status == null && !probablySpam) { // message was sent successfully response.sendRedirect("test?bodyJsp=" + confirmpage); } else { // exception occurred response.sendRedirect("test?bodyJsp=" + errpage + "&ERR=" + status); } }