List of usage examples for javax.mail.internet MimeMessage setFrom
public void setFrom(String address) throws MessagingException
From source file:com.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }/*from w w w. ja va2 s . co m*/ if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
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;/* w w w . j av a2 s . c o 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); } }
From source file:ee.cyber.licensing.service.MailService.java
public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId) throws MessagingException, IOException, SQLException { License license = licenseRepository.findById(licenseId); List<Contact> contacts = contactRepository.findAll(license.getCustomer()); List<String> receivers = getReceivers(mailbody, contacts); logger.info("1st ===> setup Mail Server Properties"); Properties mailServerProperties = getProperties(); final String email = mailServerProperties.getProperty("fromEmail"); final String password = mailServerProperties.getProperty("password"); final String host = mailServerProperties.getProperty("mail.smtp.host"); logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument"); Authenticator authentication = new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(email, password); }/* ww w .j a v a 2s. co m*/ }; logger.info("Mail Server Properties have been setup successfully"); logger.info("3rd ===> get Mail Session.."); Session getMailSession = Session.getInstance(mailServerProperties, authentication); logger.info("4th ===> generateAndSendEmail() starts"); MimeMessage mailMessage = new MimeMessage(getMailSession); mailMessage.addHeader("Content-type", "text/html; charset=UTF-8"); mailMessage.addHeader("format", "flowed"); mailMessage.addHeader("Content-Transfer-Encoding", "8bit"); mailMessage.setFrom(new InternetAddress(email, "License dude")); //mailMessage.setReplyTo(InternetAddress.parse(email, false)); mailMessage.setSubject(mailbody.getSubject()); //String emailBody = body + "<br><br> Regards, <br>Cybernetica team"; mailMessage.setSentDate(new Date()); for (String receiver : receivers) { mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver)); } if (fileId != 0) { MailAttachment file = fileRepository.findById(fileId); if (file != null) { String fileName = file.getFileName(); byte[] fileData = file.getData_b(); if (fileName != null) { // Create a multipart message for attachment Multipart multipart = new MimeMultipart(); // Body part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(mailbody.getBody(), "text/html"); multipart.addBodyPart(messageBodyPart); //Attachment part messageBodyPart = new MimeBodyPart(); ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(fileName); multipart.addBodyPart(messageBodyPart); mailMessage.setContent(multipart); } } } else { mailMessage.setContent(mailbody.getBody(), "text/html"); } logger.info("5th ===> Get Session"); sendMail(email, password, host, getMailSession, mailMessage); }
From source file:org.xwiki.mail.internal.DefaultMailSender.java
@Override public void sendAsynchronously(MimeMessage message, Session session, MailResultListener listener) { try {//from w w w . ja va 2 s .c o m // Perform some basic verification to avoid NPEs in JavaMail if (message.getFrom() == null) { // Try using the From address in the Session String from = this.configuration.getFromAddress(); if (from != null) { message.setFrom(new InternetAddress(from)); } else { throw new MessagingException("Missing the From Address for sending the mail. " + "You need to either define it in the Mail Configuration or pass it in your message."); } } // Push new mail message on the queue getMailQueue().add(new MailSenderQueueItem(message, session, listener)); } catch (Exception e) { // Save any exception in the listener listener.onError(message, e); } }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;// w ww. j a v a 2s. co m props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java
/** * Build a {@link MimeMessage} instance from the set of supplied parameters. * @return The {@link MimeMessage} instance; * @throws MessagingException//from ww w . j a v a 2 s .c om * @throws UnsupportedEncodingException */ public MimeMessage buildMimeMessage() throws MessagingException, UnsupportedEncodingException { MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession()); setJenkinsInstanceIdent(msg); msg.setContent("", contentType()); if (StringUtils.isNotBlank(from)) { msg.setFrom(toNormalizedAddress(from)); } msg.setSentDate(new Date()); addSubject(msg); addBody(msg); addRecipients(msg); if (!replyTo.isEmpty()) { msg.setReplyTo(toAddressArray(replyTo)); } return msg; }
From source file:org.apache.hupa.server.service.SendMessageBaseServiceImpl.java
/** * Create basic Message which contains all headers. No body is filled * * @param session the Session/* w ww .ja v a 2s . co m*/ * @param action the action * @return message * @throws AddressException * @throws MessagingException */ public Message createMessage(Session session, SendMessageAction 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.setSentDate(new Date()); message.addHeader("User-Agent:", "HUPA, The Apache JAMES webmail client."); message.addHeader("X-Originating-IP", getClientIpAddr()); message.setSubject(m.getSubject(), "utf-8"); updateHeaders(message, action); message.saveChanges(); return message; }
From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarRequestResetPasswordHtml.java
protected void sendPasswordResetEMail(HttpServletRequest request, ICFSecuritySecUserObj resetUser, ICFSecurityClusterObj cluster) throws AddressException, MessagingException, NamingException { final String S_ProcName = "sendPasswordResetEMail"; Properties props = System.getProperties(); String clusterDescription = cluster.getRequiredDescription(); Context ctx = new InitialContext(); String smtpEmailFrom = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpEmailFrom"); if ((smtpEmailFrom == null) || (smtpEmailFrom.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk24SmtpEmailFrom"); }//from w w w. j a va 2 s . co m smtpUsername = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpUsername"); if ((smtpUsername == null) || (smtpUsername.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk24SmtpUsername"); } smtpPassword = (String) ctx.lookup("java:comp/env/CFAsterisk24SmtpPassword"); if ((smtpPassword == null) || (smtpPassword.length() <= 0)) { throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "JNDI lookup for CFAsterisk24SmtpPassword"); } Session emailSess = Session.getInstance(props, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(smtpUsername, smtpPassword); } }); String thisURI = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getRequestURI().toString(); int lastSlash = thisURI.lastIndexOf('/'); String baseURI = thisURI.substring(0, lastSlash); UUID resetUUID = resetUser.getOptionalPasswordResetUuid(); String msgBody = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n" + "<HTML>\n" + "<BODY>\n" + "<p>\n" + "You requested a password reset for " + resetUser.getRequiredEMailAddress() + " used for accessing " + clusterDescription + ".\n" + "<p>" + "Please click on the following link to reset your password:<br>\n" + "<A HRef=\"" + baseURI + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAsteriskSMWarResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "<p>" + "Or click on the following link to cancel the reset request:<br>\n" + "<A HRef=\"" + baseURI + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "\">" + baseURI + "/CFAsteriskSMWarCancelResetPasswordHtml?ResetUUID=" + resetUUID.toString() + "</A>\n" + "</BODY>\n" + "</HTML>\n"; MimeMessage msg = new MimeMessage(emailSess); msg.setFrom(new InternetAddress(smtpEmailFrom)); InternetAddress mailTo[] = InternetAddress.parse(resetUser.getRequiredEMailAddress(), false); msg.setRecipient(Message.RecipientType.TO, mailTo[0]); msg.setSubject("You requested a password reset for your account with " + clusterDescription + "?"); msg.setContent(msgBody, "text/html"); msg.setSentDate(new Date()); msg.saveChanges(); Transport.send(msg); }
From source file:hudson.tasks.mail.impl.BaseBuildResultMail.java
/** * Creates empty mail./*from w ww. j av a 2s . c o m*/ * * @param build build. * @param listener listener. * @return empty mail. * @throws MessagingException exception if any. */ protected MimeMessage createEmptyMail(AbstractBuild<?, ?> build, BuildListener listener) throws MessagingException { MimeMessage msg = new HudsonMimeMessage(Mailer.descriptor().createSession()); // TODO: I'd like to put the URL to the page in here, // but how do I obtain that? msg.setContent("", "text/plain"); msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress())); msg.setSentDate(new Date()); Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>(); StringTokenizer tokens = new StringTokenizer(getRecipients()); while (tokens.hasMoreTokens()) { String address = tokens.nextToken(); if (address.startsWith("upstream-individuals:")) { // people who made a change in the upstream String projectName = address.substring("upstream-individuals:".length()); AbstractProject up = Hudson.getInstance().getItemByFullName(projectName, AbstractProject.class); if (up == null) { listener.getLogger().println("No such project exist: " + projectName); continue; } includeCulpritsOf(up, build, listener, rcp); } else { // ordinary address try { rcp.add(new InternetAddress(address)); } catch (AddressException e) { // report bad address, but try to send to other addresses e.printStackTrace(listener.error(e.getMessage())); } } } if (CollectionUtils.isNotEmpty(upstreamProjects)) { for (AbstractProject project : upstreamProjects) { includeCulpritsOf(project, build, listener, rcp); } } if (sendToIndividuals) { Set<User> culprits = build.getCulprits(); if (debug) listener.getLogger() .println("Trying to send e-mails to individuals who broke the build. sizeof(culprits)==" + culprits.size()); rcp.addAll(buildCulpritList(listener, culprits)); } msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()])); AbstractBuild<?, ?> pb = build.getPreviousBuild(); if (pb != null) { MailMessageIdAction b = pb.getAction(MailMessageIdAction.class); if (b != null) { msg.setHeader("In-Reply-To", b.messageId); msg.setHeader("References", b.messageId); } } return msg; }
From source file:edu.cornell.mannlib.vitro.webapp.controller.freemarker.ContactMailController.java
private void sendMessage(Session s, String webuseremail, String webusername, String[] recipients, String deliveryfrom, String msgText) throws AddressException, SendFailedException, MessagingException { // Construct the message MimeMessage msg = new MimeMessage(s); //System.out.println("trying to send message from servlet"); // Set the from address try {//ww w .j av a 2 s.co m msg.setFrom(new InternetAddress(webuseremail, webusername)); } catch (UnsupportedEncodingException e) { log.error("Can't set message sender with personal name " + webusername + " due to UnsupportedEncodingException"); msg.setFrom(new InternetAddress(webuseremail)); } // Set the recipient address InternetAddress[] address = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { address[i] = new InternetAddress(recipients[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()); Transport.send(msg); // try to send the message via smtp - catch error exceptions }