List of usage examples for javax.mail.internet MimeMessage setReplyTo
@Override public void setReplyTo(Address[] addresses) throws MessagingException
From source file:org.quartz.jobs.ee.mail.SendMailJob.java
protected MimeMessage prepareMimeMessage(MailInfo mailInfo) throws MessagingException { Session session = getMailSession(mailInfo); MimeMessage mimeMessage = new MimeMessage(session); Address[] toAddresses = InternetAddress.parse(mailInfo.getTo()); mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses); if (mailInfo.getCc() != null) { Address[] ccAddresses = InternetAddress.parse(mailInfo.getCc()); mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses); }//ww w .ja va 2s . co m mimeMessage.setFrom(new InternetAddress(mailInfo.getFrom())); if (mailInfo.getReplyTo() != null) { mimeMessage.setReplyTo(new InternetAddress[] { new InternetAddress(mailInfo.getReplyTo()) }); } mimeMessage.setSubject(mailInfo.getSubject()); mimeMessage.setSentDate(new Date()); setMimeMessageContent(mimeMessage, mailInfo); return mimeMessage; }
From source file:org.sakaiproject.email.impl.BasicEmailService.java
public void sendMailMessagingException(InternetAddress from, InternetAddress[] to, String subject, String content, Map<RecipientType, InternetAddress[]> headerTo, InternetAddress[] replyTo, List<String> additionalHeaders, List<Attachment> attachments) throws MessagingException { // some timing for debug long start = 0; if (M_log.isDebugEnabled()) start = System.currentTimeMillis(); // if in test mode, use the test method if (m_testMode) { testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders); return;/*w w w. ja v a2 s .c om*/ } if (m_smtp == null) { M_log.error( "Unable to send mail as no smtp server is defined. Please set smtp@org.sakaiproject.email.api.EmailService value in sakai.properties"); return; } if (from == null) { M_log.warn("sendMail: null from"); return; } if (to == null) { M_log.warn("sendMail: null to"); return; } if (content == null) { M_log.warn("sendMail: null content"); return; } Properties props = createMailSessionProperties(); Session session = Session.getInstance(props); // see if we have a message-id in the additional headers String mid = null; if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": ")) { // length of 'message-id: ' == 12 mid = header.substring(12); break; } } } // use the special extension that can set the id MimeMessage msg = new MyMessage(session, mid); // the FULL content-type header, for example: // Content-Type: text/plain; charset=windows-1252; format=flowed String contentTypeHeader = null; // If we need to force the container to use a certain multipart subtype // e.g. 'alternative' // then sneak it through in the additionalHeaders String multipartSubtype = null; // set the additional headers on the message // but treat Content-Type specially as we need to check the charset // and we already dealt with the message id if (additionalHeaders != null) { for (String header : additionalHeaders) { if (header.toLowerCase().startsWith(EmailHeaders.CONTENT_TYPE.toLowerCase() + ": ")) contentTypeHeader = header; else if (header.toLowerCase().startsWith(EmailHeaders.MULTIPART_SUBTYPE.toLowerCase() + ": ")) multipartSubtype = header.substring(header.indexOf(":") + 1).trim(); else if (!header.toLowerCase().startsWith(EmailHeaders.MESSAGE_ID.toLowerCase() + ": ")) msg.addHeaderLine(header); } } // date if (msg.getHeader(EmailHeaders.DATE) == null) msg.setSentDate(new Date(System.currentTimeMillis())); // set the message sender msg.setFrom(from); // set the message recipients (headers) setRecipients(headerTo, msg); // set the reply to if ((replyTo != null) && (msg.getHeader(EmailHeaders.REPLY_TO) == null)) msg.setReplyTo(replyTo); // update to be Postmaster if necessary checkFrom(msg); // figure out what charset encoding to use // // first try to use the charset from the forwarded // Content-Type header (if there is one). // // if that charset doesn't work, try a couple others. // the character set, for example, windows-1252 or UTF-8 String charset = extractCharset(contentTypeHeader); if (charset != null && canUseCharset(content, charset) && canUseCharset(subject, charset)) { // use the charset from the Content-Type header } else if (canUseCharset(content, CharacterSet.ISO_8859_1) && canUseCharset(subject, CharacterSet.ISO_8859_1)) { if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.ISO_8859_1); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.ISO_8859_1; charset = CharacterSet.ISO_8859_1; } else if (canUseCharset(content, CharacterSet.WINDOWS_1252) && canUseCharset(subject, CharacterSet.WINDOWS_1252)) { if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.WINDOWS_1252); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.WINDOWS_1252; charset = CharacterSet.WINDOWS_1252; } else { // catch-all - UTF-8 should be able to handle anything if (contentTypeHeader != null && charset != null) contentTypeHeader = contentTypeHeader.replaceAll(charset, CharacterSet.UTF_8); else if (contentTypeHeader != null) contentTypeHeader += "; charset=" + CharacterSet.UTF_8; else contentTypeHeader = EmailHeaders.CONTENT_TYPE + ": " + ContentType.TEXT_PLAIN + "; charset=" + CharacterSet.UTF_8; charset = CharacterSet.UTF_8; } if ((subject != null) && (msg.getHeader(EmailHeaders.SUBJECT) == null)) msg.setSubject(subject, charset); // extract just the content type value from the header String contentType = null; if (contentTypeHeader != null) { int colonPos = contentTypeHeader.indexOf(":"); contentType = contentTypeHeader.substring(colonPos + 1).trim(); } setContent(content, attachments, msg, contentType, charset, multipartSubtype); // if we have a full Content-Type header, set it NOW // (after setting the body of the message so that format=flowed is preserved) // if there attachments, the messsage type will default to multipart/mixed and should // stay that way. if ((attachments == null || attachments.size() == 0) && contentTypeHeader != null) { msg.addHeaderLine(contentTypeHeader); msg.addHeaderLine(EmailHeaders.CONTENT_TRANSFER_ENCODING + ": quoted-printable"); } if (M_log.isDebugEnabled()) { M_log.debug("HeaderLines received were: "); Enumeration<String> allHeaders = msg.getAllHeaderLines(); while (allHeaders.hasMoreElements()) { M_log.debug((String) allHeaders.nextElement()); } } sendMessageAndLog(from, to, subject, headerTo, start, msg, session); }
From source file:org.sakaiproject.email.impl.BasicEmailService.java
/** * fix up From and ReplyTo if we need it to be from Postmaster *//*ww w . jav a 2 s .com*/ private void checkFrom(MimeMessage msg) { String sendFromSakai = serverConfigurationService.getString(MAIL_SENDFROMSAKAI, "true"); String sendExceptions = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_EXCEPTIONS, null); InternetAddress from = null; InternetAddress[] replyTo = null; try { Address[] fromA = msg.getFrom(); if (fromA == null || fromA.length == 0) { M_log.info("message from missing"); return; } else if (fromA.length > 1) { M_log.info("message from more than 1"); return; } else if (fromA instanceof InternetAddress[]) { from = (InternetAddress) fromA[0]; } else { M_log.info("message from not InternetAddress"); return; } Address[] replyToA = msg.getReplyTo(); if (replyToA == null) replyTo = null; else if (replyToA instanceof InternetAddress[]) replyTo = (InternetAddress[]) replyToA; else { M_log.info("message replyto isn't internet address"); return; } // should we replace from address with a Sakai address? if (sendFromSakai != null && !sendFromSakai.equalsIgnoreCase("false")) { // exceptions -- addresses to leave alone. Our own addresses are always exceptions. // you can also configure a regexp of exceptions. if (!from.getAddress().toLowerCase() .endsWith("@" + serverConfigurationService.getServerName().toLowerCase()) && (sendExceptions == null || sendExceptions.equals("") || !from.getAddress().toLowerCase().matches(sendExceptions))) { // not an exception. do the replacement. // First, decide on the replacement address. The config variable // may be the replacement address. If not, use postmaster if (sendFromSakai.indexOf("@") < 0) sendFromSakai = POSTMASTER + "@" + serverConfigurationService.getServerName(); // put the original from into reply-to, unless a replyto exists if (replyTo == null || replyTo.length == 0 || replyTo[0].getAddress().equals("")) { replyTo = new InternetAddress[1]; replyTo[0] = from; msg.setReplyTo(replyTo); } // for some reason setReplyTo doesn't work, though setFrom does. Have to create the // actual header line if (msg.getHeader(EmailHeaders.REPLY_TO) == null) msg.addHeader(EmailHeaders.REPLY_TO, from.getAddress()); // and use the new from address // biggest issue is the "personal address", i.e. the comment text String origFromText = from.getPersonal(); String origFromAddress = from.getAddress(); String fromTextPattern = serverConfigurationService.getString(MAIL_SENDFROMSAKAI_FROMTEXT, "{}"); String fromText = null; if (origFromText != null && !origFromText.equals("")) fromText = fromTextPattern.replace("{}", origFromText + " (" + origFromAddress + ")"); else fromText = fromTextPattern.replace("{}", origFromAddress); from = new InternetAddress(sendFromSakai); try { from.setPersonal(fromText); } catch (Exception e) { } msg.setFrom(from); } } } catch (javax.mail.internet.AddressException e) { M_log.info("checkfrom address exception " + e); } catch (javax.mail.MessagingException e) { M_log.info("checkfrom messaging exception " + e); } }
From source file:org.sakaiproject.kernel.messaging.email.EmailMessageListener.java
public void handleMessage(Message email) throws AddressException, UnsupportedEncodingException, SendFailedException, MessagingException, IOException { String fromAddress = email.getHeader(Message.Field.FROM); if (fromAddress == null) { throw new MessagingException("Unable to send without a 'from' address."); }/*from w w w . jav a 2 s .c om*/ // transform to a MimeMessage ArrayList<String> invalids = new ArrayList<String>(); // convert and validate the 'from' address InternetAddress from = new InternetAddress(fromAddress, true); // convert and validate reply to addresses String replyTos = email.getHeader(EmailMessage.Field.REPLY_TO); InternetAddress[] replyTo = emails2Internets(replyTos, invalids); // convert and validate the 'to' addresses String tos = email.getHeader(Message.Field.TO); InternetAddress[] to = emails2Internets(tos, invalids); // convert and validate 'cc' addresses String ccs = email.getHeader(EmailMessage.Field.CC); InternetAddress[] cc = emails2Internets(ccs, invalids); // convert and validate 'bcc' addresses String bccs = email.getHeader(EmailMessage.Field.BCC); InternetAddress[] bcc = emails2Internets(bccs, invalids); int totalRcpts = to.length + cc.length + bcc.length; if (totalRcpts == 0) { throw new MessagingException("No recipients to send to."); } MimeMessage mimeMsg = new MimeMessage(session); mimeMsg.setFrom(from); mimeMsg.setReplyTo(replyTo); mimeMsg.setRecipients(RecipientType.TO, to); mimeMsg.setRecipients(RecipientType.CC, cc); mimeMsg.setRecipients(RecipientType.BCC, bcc); // add in any additional headers Map<String, String> headers = email.getHeaders(); if (headers != null && !headers.isEmpty()) { for (Entry<String, String> header : headers.entrySet()) { mimeMsg.setHeader(header.getKey(), header.getValue()); } } // add the content to the message List<Message> parts = email.getParts(); if (parts == null || parts.size() == 0) { setContent(mimeMsg, email); } else { // create a multipart container Multipart multipart = new MimeMultipart(); // create a body part for the message text MimeBodyPart msgBodyPart = new MimeBodyPart(); setContent(msgBodyPart, email); // add the message part to the container multipart.addBodyPart(msgBodyPart); // add attachments for (Message part : parts) { addPart(multipart, part); } // set the multipart container as the content of the message mimeMsg.setContent(multipart); } if (allowTransport) { // send Transport.send(mimeMsg); } else { try { ByteArrayOutputStream output = new ByteArrayOutputStream(); mimeMsg.writeTo(output); String emailString = output.toString(); LOG.info(emailString); observable.notifyObservers(emailString); } catch (IOException e) { LOG.info("Transport disabled and unable to write message to log: " + e.getMessage(), e); } } }
From source file:org.sakaiproject.tool.mailtool.Mailtool.java
public String processSendEmail() { /* EmailUser */ selected = m_recipientSelector.getSelectedUsers(); if (m_selectByTree) { selectedGroupAwareRoleUsers = m_recipientSelector1.getSelectedUsers(); selectedGroupUsers = m_recipientSelector2.getSelectedUsers(); selectedSectionUsers = m_recipientSelector3.getSelectedUsers(); selected.addAll(selectedGroupAwareRoleUsers); selected.addAll(selectedGroupUsers); selected.addAll(selectedSectionUsers); }/*from ww w. ja v a 2 s . c o m*/ // Put everyone in a set so the same person doesn't get multiple emails. Set emailusers = new TreeSet(); if (isAllUsersSelected()) { // the button for this is inactivated ... leave for future for (Iterator i = getEmailGroups().iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); emailusers.addAll(group.getEmailusers()); } } if (isAllGroupSelected()) { for (Iterator i = getEmailGroupsByType("section").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("section")) { selected.addAll(group.getEmailusers()); } } } if (isAllSectionSelected()) { for (Iterator i = getEmailGroupsByType("group").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("group")) { selected.addAll(group.getEmailusers()); } } } if (isAllGroupAwareRoleSelected()) { for (Iterator i = getEmailGroupsByType("role_groupaware").iterator(); i.hasNext();) { EmailGroup group = (EmailGroup) i.next(); if (group.getEmailrole().roletype.equals("role_groupaware")) { selected.addAll(group.getEmailusers()); } } } emailusers = new TreeSet(selected); // convert List to Set (remove duplicates) m_subjectprefix = getSubjectPrefixFromConfig(); EmailUser curUser = getCurrentUser(); String fromEmail = ""; String fromDisplay = ""; if (curUser != null) { fromEmail = curUser.getEmail(); fromDisplay = curUser.getDisplayname(); } String fromString = fromDisplay + " <" + fromEmail + ">"; m_results = "Message sent to: <br>"; String subject = m_subject; //Should we append this to the archive? String emailarchive = "/mailarchive/channel/" + m_siteid + "/main"; if (m_archiveMessage && isEmailArchiveInSite()) { String attachment_info = "<br/>"; Attachment a = null; Iterator iter = attachedFiles.iterator(); int i = 0; while (iter.hasNext()) { a = (Attachment) iter.next(); attachment_info += "<br/>"; attachment_info += "Attachment #" + (i + 1) + ": " + a.getFilename() + "(" + a.getSize() + " Bytes)"; i++; } this.appendToArchive(emailarchive, fromString, subject, m_body + attachment_info); } List headers = new ArrayList(); if (getTextFormat().equals("htmltext")) headers.add("content-type: text/html"); else headers.add("content-type: text/plain"); String smtp_server = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService"); //String smtp_port = ServerConfigurationService.getString("smtp.port"); try { Properties props = new Properties(); props.put("mail.smtp.host", smtp_server); //props.put("mail.smtp.port", smtp_port); Session s = Session.getInstance(props, null); MimeMessage message = new MimeMessage(s); InternetAddress from = new InternetAddress(fromString); message.setFrom(from); String reply = getReplyToSelected().trim().toLowerCase(); if (reply.equals("yes")) { // "reply to sender" is default. So do nothing } else if (reply.equals("no")) { String noreply = getSiteTitle() + " <noreply@" + smtp_server + ">"; InternetAddress noreplyemail = new InternetAddress(noreply); message.setFrom(noreplyemail); } else if (reply.equals("otheremail") && getReplyToOtherEmail().equals("") != true) { // need input(email) validation InternetAddress replytoList[] = { new InternetAddress(getConfigParam("replyto").trim()) }; message.setReplyTo(replytoList); } message.setSubject(subject); String text = m_body; String attachmentdirectory = getUploadDirectory(); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message String messagetype = ""; if (getTextFormat().equals("htmltext")) { messagetype = "text/html"; } else { messagetype = "text/plain"; } messageBodyPart.setContent(text, messagetype); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment Attachment a = null; Iterator iter = attachedFiles.iterator(); while (iter.hasNext()) { a = (Attachment) iter.next(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource( attachmentdirectory + this.getCurrentUser().getUserid() + "-" + a.getFilename()); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(a.getFilename()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); //Send the emails String recipientsString = ""; for (Iterator i = emailusers.iterator(); i.hasNext(); recipientsString += ",") { EmailUser euser = (EmailUser) i.next(); String toEmail = euser.getEmail(); // u.getEmail(); String toDisplay = euser.getDisplayname(); // u.getDisplayName(); // if AllUsers are selected, do not add current user's email to recipients if (isAllUsersSelected() && getCurrentUser().getEmail().equals(toEmail)) { // don't add sender to recipients } else { recipientsString += toEmail; m_results += toDisplay + (i.hasNext() ? "<br/>" : ""); } // InternetAddress to[] = {new InternetAddress(toEmail) }; // Transport.send(message,to); } if (m_otheremails.trim().equals("") != true) { // // multiple email validation is needed here // String refinedOtherEmailAddresses = m_otheremails.trim().replace(';', ','); recipientsString += refinedOtherEmailAddresses; m_results += "<br/>" + refinedOtherEmailAddresses; // InternetAddress to[] = {new InternetAddress(refinedOtherEmailAddresses) }; // Transport.send(message, to); } if (m_sendmecopy) { message.addRecipients(Message.RecipientType.CC, fromEmail); // trying to solve SAK-7410 // recipientsString+=fromEmail; // InternetAddress to[] = {new InternetAddress(fromEmail) }; // Transport.send(message, to); } // message.addRecipients(Message.RecipientType.TO, recipientsString); message.addRecipients(Message.RecipientType.BCC, recipientsString); Transport.send(message); } catch (Exception e) { log.debug("Mailtool Exception while trying to send the email: " + e.getMessage()); } // Clear the Subject and Body of the Message m_subject = getSubjectPrefix().equals("") ? getSubjectPrefixFromConfig() : getSubjectPrefix(); m_otheremails = ""; m_body = ""; num_files = 0; attachedFiles.clear(); m_recipientSelector = null; m_recipientSelector1 = null; m_recipientSelector2 = null; m_recipientSelector3 = null; setAllUsersSelected(false); setAllGroupSelected(false); setAllSectionSelected(false); // Display Users with Bad Emails if the option is turned on. boolean showBadEmails = getDisplayInvalidEmailAddr(); if (showBadEmails == true) { m_results += "<br/><br/>"; List /* String */ badnames = new ArrayList(); for (Iterator i = selected.iterator(); i.hasNext();) { EmailUser user = (EmailUser) i.next(); /* This check should maybe be some sort of regular expression */ if (user.getEmail().equals("")) { badnames.add(user.getDisplayname()); } } if (badnames.size() > 0) { m_results += "The following users do not have valid email addresses:<br/>"; for (Iterator i = badnames.iterator(); i.hasNext();) { String name = (String) i.next(); if (i.hasNext() == true) m_results += name + "/ "; else m_results += name; } } } return "results"; }
From source file:org.silverpeas.core.mail.engine.SmtpMailSender.java
@Override public void send(final MailToSend mail) { SmtpConfiguration smtpConfiguration = SmtpConfiguration.fromDefaultSettings(); MailAddress fromMailAddress = mail.getFrom(); Session session = getMailSession(smtpConfiguration); try {/*w w w .j av a2 s .c om*/ InternetAddress fromAddress = fromMailAddress.getAuthorizedInternetAddress(); InternetAddress replyToAddress = null; List<InternetAddress[]> toAddresses = new ArrayList<>(); // Parsing destination address for compliance with RFC822. final Collection<ReceiverMailAddressSet> addressBatches = mail.getTo().getBatchedReceiversList(); for (ReceiverMailAddressSet addressBatch : addressBatches) { try { toAddresses.add(InternetAddress.parse(addressBatch.getEmailsSeparatedByComma(), false)); } catch (AddressException e) { SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE", "From = " + fromMailAddress + ", To = " + addressBatch.getEmailsSeparatedByComma(), e); } } try { if (mail.isReplyToRequired()) { replyToAddress = new InternetAddress(fromMailAddress.getEmail(), false); if (StringUtil.isDefined(fromMailAddress.getName())) { replyToAddress.setPersonal(fromMailAddress.getName(), Charsets.UTF_8.name()); } } } catch (AddressException e) { SilverTrace.warn("mail", "MailSender.send()", "root.MSG_GEN_PARAM_VALUE", "ReplyTo = " + fromMailAddress + " is malformed.", e); } MimeMessage email = new MimeMessage(session); email.setFrom(fromAddress); if (replyToAddress != null) { email.setReplyTo(new InternetAddress[] { replyToAddress }); } email.setHeader("Precedence", "list"); email.setHeader("List-ID", fromAddress.getAddress()); email.setSentDate(new Date()); email.setSubject(mail.getSubject(), CharEncoding.UTF_8); mail.getContent().applyOn(email); // Sending. performSend(mail, smtpConfiguration, session, email, toAddresses); } catch (MessagingException | UnsupportedEncodingException e) { SilverLogger.getLogger(this).error(e.getMessage(), e); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.talend.dataprep.api.service.mail.MailFeedbackSender.java
@Override public void send(String subject, String body, String sender) { try {// w w w . jav a2 s .com final String recipientList = StringUtils.join((new HashSet<>(Arrays.asList(recipients))).toArray(), ','); subject = subjectPrefix + subject; body = bodyPrefix + "<br/>" + body + "<br/>" + bodySuffix; InternetAddress from = new InternetAddress(this.sender); InternetAddress replyTo = new InternetAddress(sender); Properties p = new Properties(); p.put("mail.smtp.host", smtpHost); p.put("mail.smtp.port", smtpPort); p.put("mail.smtp.starttls.enable", "true"); p.put("mail.smtp.auth", "true"); MailAuthenticator authenticator = new MailAuthenticator(userName, password); Session sendMailSession = Session.getInstance(p, authenticator); MimeMessage msg = new MimeMessage(sendMailSession); msg.setFrom(from); msg.setReplyTo(new Address[] { replyTo }); msg.addRecipients(Message.RecipientType.TO, recipientList); msg.setSubject(subject, "UTF-8"); msg.setSentDate(new Date()); Multipart mainPart = new MimeMultipart(); BodyPart html = new MimeBodyPart(); html.setContent(body, "text/html; charset=utf-8"); mainPart.addBodyPart(html); msg.setContent(mainPart); Transport.send(msg); LOGGER.debug("Sending mail:'{}' to '{}'", subject, recipients); } catch (Exception e) { throw new TDPException(APIErrorCodes.UNABLE_TO_SEND_MAIL, e); } }
From source file:org.xwiki.commons.internal.DefaultMailSender.java
@Override public int send(Mail mail) { Session session = null;//from ww w . ja v a2s.c om Transport transport = null; if ((mail.getTo() == null || StringUtils.isEmpty(mail.getTo())) && (mail.getCc() == null || StringUtils.isEmpty(mail.getCc())) && (mail.getBcc() == null || StringUtils.isEmpty(mail.getBcc()))) { logger.error("This mail has no recipient"); return 0; } if (mail.getContents().size() == 0) { logger.error("This mail is empty. You should add a content"); return 0; } try { if ((transport == null) || (session == null)) { logger.info("Sending mail : Initializing properties"); Properties props = initProperties(); session = Session.getInstance(props, null); transport = session.getTransport("smtp"); if (session.getProperty("mail.smtp.auth") == "true") transport.connect(session.getProperty("mail.smtp.server.username"), session.getProperty("mail.smtp.server.password")); else transport.connect(); try { Multipart wrapper = generateMimeMultipart(mail); InternetAddress[] adressesTo = this.toInternetAddresses(mail.getTo()); MimeMessage message = new MimeMessage(session); message.setSentDate(new Date()); message.setSubject(mail.getSubject()); message.setFrom(new InternetAddress(mail.getFrom())); message.setRecipients(javax.mail.Message.RecipientType.TO, adressesTo); if (mail.getReplyTo() != null && !StringUtils.isEmpty(mail.getReplyTo())) { logger.info("Adding ReplyTo field"); InternetAddress[] adressesReplyTo = this.toInternetAddresses(mail.getReplyTo()); if (adressesReplyTo.length != 0) message.setReplyTo(adressesReplyTo); } if (mail.getCc() != null && !StringUtils.isEmpty(mail.getCc())) { logger.info("Adding Cc recipients"); InternetAddress[] adressesCc = this.toInternetAddresses(mail.getCc()); if (adressesCc.length != 0) message.setRecipients(javax.mail.Message.RecipientType.CC, adressesCc); } if (mail.getBcc() != null && !StringUtils.isEmpty(mail.getBcc())) { InternetAddress[] adressesBcc = this.toInternetAddresses(mail.getBcc()); if (adressesBcc.length != 0) message.setRecipients(javax.mail.Message.RecipientType.BCC, adressesBcc); } message.setContent(wrapper); message.setSentDate(new Date()); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (SendFailedException sfex) { logger.error("Error encountered while trying to send the mail"); logger.error("SendFailedException has occured.", sfex); try { transport.close(); } catch (MessagingException Mex) { logger.error("MessagingException has occured.", Mex); } return 0; } catch (MessagingException mex) { logger.error("Error encountered while trying to send the mail"); logger.error("MessagingException has occured.", mex); try { transport.close(); } catch (MessagingException ex) { logger.error("MessagingException has occured.", ex); } return 0; } } } catch (Exception e) { System.out.println(e.toString()); logger.error("Error encountered while trying to setup mail properties"); try { if (transport != null) { transport.close(); } } catch (MessagingException ex) { logger.error("MessagingException has occured.", ex); } return 0; } return 1; }