List of usage examples for javax.mail Session getTransport
public Transport getTransport(Address address) throws NoSuchProviderException
From source file:com.evolveum.midpoint.notifications.impl.api.transports.MailTransport.java
@Override public void send(Message mailMessage, String transportName, Task task, OperationResult parentResult) { OperationResult result = parentResult.createSubresult(DOT_CLASS + "send"); result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo()); result.addParam("mailMessage subject", mailMessage.getSubject()); SystemConfigurationType systemConfiguration = NotificationsUtil .getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy")); if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) { String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent."; LOGGER.warn(msg);//from w w w . j a va 2 s. c o m result.recordWarning(msg); return; } MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail(); String redirectToFile = mailConfigurationType.getRedirectToFile(); if (redirectToFile != null) { try { TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage)); result.recordSuccess(); } catch (IOException e) { LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile); result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e); } return; } if (mailConfigurationType.getServer().isEmpty()) { String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent."; LOGGER.warn(msg); result.recordWarning(msg); return; } long start = System.currentTimeMillis(); String from = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org"; for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) { OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer"); final String host = mailServerConfigurationType.getHost(); resultForServer.addContext("server", host); resultForServer.addContext("port", mailServerConfigurationType.getPort()); Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); if (mailServerConfigurationType.getPort() != null) { properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort())); } MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType .getTransportSecurity(); boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false; switch (mailTransportSecurityType) { case STARTTLS_ENABLED: starttlsEnable = true; break; case STARTTLS_REQUIRED: starttlsEnable = true; starttlsRequired = true; break; case SSL: sslEnabled = true; break; } properties.put("mail.smtp.ssl.enable", "" + sslEnabled); properties.put("mail.smtp.starttls.enable", "" + starttlsEnable); properties.put("mail.smtp.starttls.required", "" + starttlsRequired); if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) { properties.put("mail.debug", "true"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using mail properties: "); for (Object key : properties.keySet()) { if (key instanceof String && ((String) key).startsWith("mail.")) { LOGGER.debug(" - " + key + " = " + properties.get(key)); } } } task.recordState("Sending notification mail via " + host); Session session = Session.getInstance(properties); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(from)); for (String recipient : mailMessage.getTo()) { mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); } mimeMessage.setSubject(mailMessage.getSubject(), "utf-8"); String contentType = mailMessage.getContentType(); if (StringUtils.isEmpty(contentType)) { contentType = "text/plain; charset=UTF-8"; } mimeMessage.setContent(mailMessage.getBody(), contentType); javax.mail.Transport t = session.getTransport("smtp"); if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) { ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword(); String password = null; if (passwordProtected != null) { try { password = protector.decryptString(passwordProtected); } catch (EncryptionException e) { String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any."; LoggingUtils.logException(LOGGER, msg, e); resultForServer.recordFatalError(msg, e); continue; } } t.connect(mailServerConfigurationType.getUsername(), password); } else { t.connect(); } t.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + "."); resultForServer.recordSuccess(); result.recordSuccess(); long duration = System.currentTimeMillis() - start; task.recordState( "Notification mail sent successfully via " + host + ", in " + duration + " ms overall."); task.recordNotificationOperation(NAME, true, duration); return; } catch (MessagingException e) { String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any"; LoggingUtils.logException(LOGGER, msg, e); resultForServer.recordFatalError(msg, e); task.recordState("Error sending notification mail via " + host); } } LOGGER.warn( "No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent."); result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent."); task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start); }
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)); }// w ww. ja v a 2s.c o 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:mx.uatx.tesis.managebeans.IndexMB.java
public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception { try {/*from w w w . j av a2 s. c om*/ // Propiedades de la conexin Properties props = new Properties(); props.setProperty("mail.smtp.host", "smtp.gmail.com"); props.setProperty("mail.smtp.starttls.enable", "true"); props.setProperty("mail.smtp.port", "587"); props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com"); props.setProperty("mail.smtp.auth", "true"); // Preparamos la sesion Session session = Session.getDefaultInstance(props); // Construimos el mensaje MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress("alfons018pbg@gmail.com")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + "")); message.setSubject("Asistencia tcnica"); message.setText("\n \n \n Estimado: " + nombre + " " + apellido + "\n El Servicio Tecnico de SEA ta da la bienvenida. " + "\n Los siguientes son tus datos para acceder:" + "\n Correo: " + corre + "\n Password: " + password2 + ""); // Lo enviamos. Transport t = session.getTransport("smtp"); t.connect("alfons018pbg@gmail.com", "al12fo05zo1990"); t.sendMessage(message, message.getAllRecipients()); // Cierre. t.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.fsrin.menumine.common.message.MailSenderImpl.java
/** * @see com.ess.messages.MailSender#send() *///from www .jav a 2s.c o m public boolean send() { try { Properties props = new Properties(); props.put("mail.smtp.host", host.getAddress()); if (host.useAuthentication()) { props.put("mail.smtp.auth", "true"); } Session s = Session.getInstance(props, null); s.setDebug(true); // PasswordAuthentication pa = new PasswordAuthentication(host // .getUsername(), host.getPassword()); // // URLName url = new URLName(host.getAddress()); // // s.setPasswordAuthentication(url, pa); MimeMessage messageOut = new MimeMessage(s); InternetAddress fromOut = new InternetAddress(from.getAddress()); //reid 2004-12-20 fromOut.setPersonal(from.getName()); messageOut.setFrom(fromOut); InternetAddress toOut = new InternetAddress(this.to.getAddress()); //reid 2004-12-20 toOut.setPersonal(to.getName()); messageOut.addRecipient(javax.mail.Message.RecipientType.TO, toOut); messageOut.setSubject(message.getSubject()); messageOut.setText(message.getMessage()); if (host.useAuthentication()) { Transport transport = s.getTransport("smtp"); transport.connect(host.getAddress(), host.getUsername(), host.getPassword()); transport.sendMessage(messageOut, messageOut.getAllRecipients()); transport.close(); } else { Transport.send(messageOut); } } catch (Exception e) { log.info("\n\nMailSenderIMPL3: " + host.getAddress()); e.printStackTrace(); throw new RuntimeException(e); } return true; }
From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java
/** * This is the actual java mail execution. * * @param notification/* ww w. jav a2 s .c om*/ */ private void send(EmailTemplate notification) { String from = notification.getFrom(); String to = notification.getTo(); String subject = notification.getSubject(); String style = notification.getStyle(); // body of the email is set and all substitutions of variables are made String body = notification.getBody(); // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", smtpHost); props.put("mail.smtps.port", smtpPort); props.put("mail.smtps.auth", smtpUseAuth ? "true" : "false"); // if (smtpUseAuth) { // // props.setProperty("mail.smtp.auth", smtpUseAuth + ""); // props.setProperty("mail.username", smtpUsername); // props.setProperty("mail.password", smtpPassword); // // } // Get the default Session object. Session session = Session.getDefaultInstance(props); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); try { // Set the RFC 822 "From" header field using the // value of the InternetAddress.getLocalAddress method. message.setFrom(new InternetAddress(from)); // Add the given addresses to the specified recipient type. message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set the "Subject" header field. message.setSubject(subject); // Sets the given String as this part's content, // with a MIME type of "text/html". message.setContent(style + body, "text/html"); if (smtpUseAuth) { // Send message Transport tr = session.getTransport(smtpProtocol); tr.connect(smtpHost, smtpPort, smtpUsername, smtpPassword); message.saveChanges(); tr.sendMessage(message, message.getAllRecipients()); tr.close(); } else { Transport.send(message); } } catch (AddressException e) { log.error("Email Exception: Cannot connect to email host: " + smtpHost, e); } catch (MessagingException e) { log.error("Email Exception: Cannot send email message", e); } }
From source file:org.xwiki.commons.internal.DefaultMailSender.java
@Override public int send(Mail mail) { Session session = null; Transport transport = null;/*from w w w .j a va 2 s. c o m*/ 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; }
From source file:userInterface.HospitalAdminRole.ManagePatientsJPanel.java
public void sendMailToCommunityMember(String to, String subject, String message, String from, String password) { String host = "smtp.gmail.com"; Properties props = System.getProperties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", 587); props.put("mail.smtp.user", from); Session session = Session.getDefaultInstance(props); MimeMessage mimeMessage = new MimeMessage(session); try {/* w w w . j a v a2 s .co m*/ mimeMessage.setFrom(new InternetAddress(from)); mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); mimeMessage.setSubject("Alert from Hospital Organization"); mimeMessage.setText(message); SMTPTransport transport = (SMTPTransport) session.getTransport("smtps"); transport.connect(host, from, password); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (MessagingException me) { } }
From source file:net.spfbl.core.Core.java
public static synchronized boolean sendMessage(Message message, int timeout) throws Exception { if (message == null) { return false; } else if (isDirectSMTP()) { Server.logInfo("sending e-mail message."); Server.logSendMTP("authenticate: false."); Server.logSendMTP("start TLS: true."); Properties props = System.getProperties(); props.put("mail.smtp.auth", "false"); props.put("mail.smtp.port", "25"); props.put("mail.smtp.timeout", Integer.toString(timeout)); props.put("mail.smtp.connectiontimeout", "3000"); InternetAddress[] recipients = (InternetAddress[]) message.getAllRecipients(); Exception lastException = null; for (InternetAddress recipient : recipients) { String domain = Domain.normalizeHostname(recipient.getAddress(), false); for (String mx : Reverse.getMXSet(domain)) { mx = mx.substring(1);/* w w w .ja v a 2 s . c om*/ props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", mx); props.put("mail.smtp.ssl.trust", mx); InternetAddress[] recipientAlone = new InternetAddress[1]; recipientAlone[0] = (InternetAddress) recipient; Session session = Session.getDefaultInstance(props); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); try { transport.setLocalHost(HOSTNAME); Server.logSendMTP("connecting to " + mx + ":25."); transport.connect(mx, 25, null, null); Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipient + "."); transport.sendMessage(message, recipientAlone); Server.logSendMTP("message '" + message.getSubject() + "' sent to " + recipient + "."); Server.logSendMTP("last response: " + transport.getLastServerResponse()); lastException = null; break; } catch (MailConnectException ex) { Server.logSendMTP("connection failed."); lastException = ex; } catch (SendFailedException ex) { Server.logSendMTP("send failed."); throw ex; } catch (MessagingException ex) { if (ex.getMessage().contains(" TLS ")) { Server.logSendMTP("cannot establish TLS connection."); if (transport.isConnected()) { transport.close(); Server.logSendMTP("connection closed."); } Server.logInfo("sending e-mail message without TLS."); props.put("mail.smtp.starttls.enable", "false"); session = Session.getDefaultInstance(props); transport = (SMTPTransport) session.getTransport("smtp"); try { transport.setLocalHost(HOSTNAME); Server.logSendMTP("connecting to " + mx + ":25."); transport.connect(mx, 25, null, null); Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipient + "."); transport.sendMessage(message, recipientAlone); Server.logSendMTP( "message '" + message.getSubject() + "' sent to " + recipient + "."); Server.logSendMTP("last response: " + transport.getLastServerResponse()); lastException = null; break; } catch (SendFailedException ex2) { Server.logSendMTP("send failed."); throw ex2; } catch (Exception ex2) { lastException = ex2; } } else { lastException = ex; } } catch (Exception ex) { Server.logError(ex); lastException = ex; } finally { if (transport.isConnected()) { transport.close(); Server.logSendMTP("connection closed."); } } } } if (lastException == null) { return true; } else { throw lastException; } } else if (hasRelaySMTP()) { Server.logInfo("sending e-mail message."); Server.logSendMTP("authenticate: " + Boolean.toString(SMTP_IS_AUTH) + "."); Server.logSendMTP("start TLS: " + Boolean.toString(SMTP_STARTTLS) + "."); Properties props = System.getProperties(); props.put("mail.smtp.auth", Boolean.toString(SMTP_IS_AUTH)); props.put("mail.smtp.starttls.enable", Boolean.toString(SMTP_STARTTLS)); props.put("mail.smtp.host", SMTP_HOST); props.put("mail.smtp.port", Short.toString(SMTP_PORT)); props.put("mail.smtp.timeout", Integer.toString(timeout)); props.put("mail.smtp.connectiontimeout", "3000"); props.put("mail.smtp.ssl.trust", SMTP_HOST); Address[] recipients = message.getAllRecipients(); TreeSet<String> recipientSet = new TreeSet<String>(); for (Address recipient : recipients) { recipientSet.add(recipient.toString()); } Session session = Session.getDefaultInstance(props); SMTPTransport transport = (SMTPTransport) session.getTransport("smtp"); try { if (HOSTNAME != null) { transport.setLocalHost(HOSTNAME); } Server.logSendMTP("connecting to " + SMTP_HOST + ":" + SMTP_PORT + "."); transport.connect(SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASSWORD); Server.logSendMTP("sending '" + message.getSubject() + "' to " + recipientSet + "."); transport.sendMessage(message, recipients); Server.logSendMTP("message '" + message.getSubject() + "' sent to " + recipientSet + "."); return true; } catch (SendFailedException ex) { Server.logSendMTP("send failed."); throw ex; } catch (AuthenticationFailedException ex) { Server.logSendMTP("authentication failed."); return false; } catch (MailConnectException ex) { Server.logSendMTP("connection failed."); return false; } catch (MessagingException ex) { Server.logSendMTP("messaging failed."); return false; } catch (Exception ex) { Server.logError(ex); return false; } finally { if (transport.isConnected()) { transport.close(); Server.logSendMTP("connection closed."); } } } else { return false; } }
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Send a Collection of Mails (multiple emails) * /* w w w .j ava2s .c o m*/ * @param emails Mail Collection * @return True in any case (TODO ?) */ public boolean sendMails(Collection<Mail> emails, MailConfiguration mailConfiguration, XWikiContext context) throws MessagingException, UnsupportedEncodingException { Session session = null; Transport transport = null; int emailCount = emails.size(); int count = 0; int sendFailedCount = 0; try { for (Iterator<Mail> emailIt = emails.iterator(); emailIt.hasNext();) { count++; Mail mail = emailIt.next(); LOGGER.info("Sending email: " + mail.toString()); if ((transport == null) || (session == null)) { // initialize JavaMail Session and Transport Properties props = initProperties(mailConfiguration); session = Session.getInstance(props, null); transport = session.getTransport("smtp"); if (!mailConfiguration.usesAuthentication()) { // no auth info - typical 127.0.0.1 open relay scenario transport.connect(); } else { // auth info present - typical with external smtp server transport.connect(mailConfiguration.getSmtpUsername(), mailConfiguration.getSmtpPassword()); } } try { MimeMessage message = createMimeMessage(mail, session, context); if (message == null) { continue; } transport.sendMessage(message, message.getAllRecipients()); // close the connection every other 100 emails if ((count % 100) == 0) { try { if (transport != null) { transport.close(); } } catch (MessagingException ex) { LOGGER.error("MessagingException has occured.", ex); } transport = null; session = null; } } catch (SendFailedException ex) { sendFailedCount++; LOGGER.error("SendFailedException has occured.", ex); LOGGER.error("Detailed email information" + mail.toString()); if (emailCount == 1) { throw ex; } if ((emailCount != 1) && (sendFailedCount > 10)) { throw ex; } } catch (MessagingException mex) { LOGGER.error("MessagingException has occured.", mex); LOGGER.error("Detailed email information" + mail.toString()); if (emailCount == 1) { throw mex; } } catch (XWikiException e) { LOGGER.error("XWikiException has occured.", e); } catch (IOException e) { LOGGER.error("IOException has occured.", e); } } } finally { try { if (transport != null) { transport.close(); } } catch (MessagingException ex) { LOGGER.error("MessagingException has occured.", ex); } LOGGER.info("sendEmails: Email count = " + emailCount + " sent count = " + count); } return true; }
From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java
@Override @TransactionAttribute(TransactionAttributeType.REQUIRED) public void onMessage(Message arg0) { ObjectMessage objectMessage = (ObjectMessage) arg0; try {// w w w.j a v a2 s. c o m Mail mail = (Mail) objectMessage.getObject(); // Get properties String mailProtocol = getMailProtocol(); String mailServer = getSmtpServer(); String mailUser = getSmtpUser(); String mailPort = getSmtpPort(); String mailPassword = getSmtpPassword(); // Initialize a mail session Properties props = new Properties(); props.put("mail." + mailProtocol + ".host", mailServer); props.put("mail." + mailProtocol + ".port", mailPort); Session session = Session.getInstance(props); // Create the message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(mail.getSender())); for (String recipient : mail.getRecipients()) { msg.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } msg.setSubject(mail.getSubject(), "UTF-8"); Multipart multipart = new MimeMultipart(); msg.setContent(multipart); // Set the email message text and attachment MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setContent(mail.getBody(), mail.getContentType()); multipart.addBodyPart(messagePart); if (mail.getAttachmentData() != null) { ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(), mail.getAttachmentContentType()); DataHandler dataHandler = new DataHandler(byteArrayDataSource); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(dataHandler); attachmentPart.setFileName(mail.getAttachmentFileName()); multipart.addBodyPart(attachmentPart); } // Open transport and send message Transport transport = session.getTransport(mailProtocol); if (StringUtils.isNotBlank(mailUser)) { transport.connect(mailUser, mailPassword); } else { transport.connect(); } msg.saveChanges(); transport.sendMessage(msg, msg.getAllRecipients()); } catch (JMSException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e); throw new RuntimeException(e); } catch (MessagingException e) { errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e); throw new RuntimeException(e); } }