List of usage examples for javax.mail Transport sendMessage
public abstract void sendMessage(Message msg, Address[] addresses) throws MessagingException;
From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java
public boolean dispatch(BIObject document, byte[] executionOutput) { String contentType;/* ww w.j a v a2 s .c om*/ String fileExtension; String nameSuffix; JobExecutionContext jobExecutionContext; logger.debug("IN"); try { contentType = dispatchContext.getContentType(); fileExtension = dispatchContext.getFileExtension(); nameSuffix = dispatchContext.getNameSuffix(); jobExecutionContext = dispatchContext.getJobExecutionContext(); //Custom Trusted Store Certificate Options String trustedStorePath = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.file"); String trustedStorePassword = SingletonConfig.getInstance() .getConfigValue("MAIL.PROFILES.trustedStore.password"); String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; int smptPort = 25; if ((smtpport == null) || smtpport.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smptPort = Integer.parseInt(smtpport); } String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); /* if( (user==null) || user.trim().equals("")) throw new Exception("Smtp user not configured"); if( (pass==null) || pass.trim().equals("")) throw new Exception("Smtp password not configured"); */ String mailTos = ""; List dlIds = dispatchContext.getDlIds(); Iterator it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); List emails = new ArrayList(); emails = dl.getEmails(); Iterator j = emails.iterator(); while (j.hasNext()) { Email e = (Email) j.next(); String email = e.getEmail(); String userTemp = e.getUserId(); IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp); if (ObjectsAccessVerifier.canSee(document, userProfile)) { if (j.hasNext()) { mailTos = mailTos + email + ","; } else { mailTos = mailTos + email; } } } } if ((mailTos == null) || mailTos.trim().equals("")) { throw new Exception("No recipient address found"); } String[] recipients = mailTos.split(","); //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.port", Integer.toString(smptPort)); Session session = null; if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) { props.put("mail.smtp.auth", "false"); session = Session.getInstance(props); logger.debug("Connecting to mail server without authentication"); } else { props.put("mail.smtp.auth", "true"); Authenticator auth = new SMTPAuthenticator(user, pass); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } session = Session.getInstance(props, auth); logger.debug("Connecting to mail server with authentication"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); 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); // Setting the Subject and Content Type IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder(); String subject = document.getName() + nameSuffix; msg.setSubject(subject); // create and fill the first message part //MimeBodyPart mbp1 = new MimeBodyPart(); //mbp1.setText(mailTxt); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType, document.getName() + nameSuffix + fileExtension); mbp2.setDataHandler(new DataHandler(sds)); mbp2.setFileName(sds.getName()); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); //mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); // add the Multipart to the message msg.setContent(mp); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smptPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { //Use normal SMTP Transport.send(msg); } if (jobExecutionContext.getNextFireTime() == null) { String triggername = jobExecutionContext.getTrigger().getName(); dlIds = dispatchContext.getDlIds(); it = dlIds.iterator(); while (it.hasNext()) { Integer dlId = (Integer) it.next(); DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId); DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl, (document.getId()).intValue(), triggername); } } } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:org.wandora.piccolo.actions.SendEmail.java
public void doAction(User user, javax.servlet.ServletRequest request, javax.servlet.ServletResponse response, Application application) {/* www . j a v a 2s. c o m*/ try { Properties props = new Properties(); props.put("mail.smtp.host", smtpServer); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); if (subject != null) message.setSubject(subject); if (from != null) message.setFrom(new InternetAddress(from)); Vector<String> recipients = new Vector<String>(); if (recipient != null) { String[] rs = recipient.split(","); String r = null; for (int i = 0; i < rs.length; i++) { r = rs[i]; if (r != null) recipients.add(r); } } MimeMultipart multipart = new MimeMultipart(); Template template = application.getTemplate(emailTemplate, user); HashMap context = new HashMap(); context.put("request", request); context.put("message", message); context.put("recipients", recipients); context.put("emailhelper", new MailHelper()); context.put("multipart", multipart); context.putAll(application.getDefaultContext(user)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); template.process(context, baos); MimeBodyPart mimeBody = new MimeBodyPart(); mimeBody.setContent(new String(baos.toByteArray(), template.getEncoding()), template.getMimeType()); // mimeBody.setContent(baos.toByteArray(),template.getMimeType()); multipart.addBodyPart(mimeBody); message.setContent(multipart); Transport transport = session.getTransport("smtp"); transport.connect(smtpServer, smtpUser, smtpPass); Address[] recipientAddresses = new Address[recipients.size()]; for (int i = 0; i < recipientAddresses.length; i++) { recipientAddresses[i] = new InternetAddress(recipients.elementAt(i)); } transport.sendMessage(message, recipientAddresses); } catch (Exception e) { logger.writelog("WRN", e); } }
From source file:com.gcrm.util.mail.MailService.java
public void sendSystemSimpleMail(String toAddress, String subject, String text) throws Exception { List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName()); EmailSetting emailSetting = null;//from w w w. j a v a 2 s.co m if (emailSettings != null && emailSettings.size() > 0) { emailSetting = emailSettings.get(0); } else { return; } Session mailSession = this.createSmtpSession(emailSetting); if (mailSession != null) { Transport transport = mailSession.getTransport(); MimeMessage msg = new MimeMessage(mailSession); MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8"); helper.setFrom(emailSetting.getFrom_address()); helper.setTo(toAddress); helper.setSubject(subject); helper.setText(text, true); transport.connect(); transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO)); } }
From source file:org.springframework.ws.transport.mail.MailSenderConnection.java
@Override protected void onSendAfterWrite(WebServiceMessage message) throws IOException { Transport transport = null; try {//from ww w . jav a2 s .c om requestMessage.setDataHandler( new DataHandler(new ByteArrayDataSource(requestContentType, requestBuffer.toByteArray()))); transport = session.getTransport(transportUri); transport.connect(); requestMessage.saveChanges(); transport.sendMessage(requestMessage, requestMessage.getAllRecipients()); } catch (MessagingException ex) { throw new MailTransportException(ex); } finally { MailTransportUtils.closeService(transport); } }
From source file:cz.filmtit.userspace.Emailer.java
/** * Sends an email with parameters that has been collected before in the fields of the class. * @return Sign if the email has been successfully sent *///from w ww . j a v a 2 s. c om public boolean send() { if (hasCollectedData()) { // send mail; javax.mail.Session session; logger.info("Emailer", "Create session for mail login " + (String) configuration.getProperty("mail.filmtit.address") + " password" + (String) configuration.getProperty("mail.filmtit.password")); session = javax.mail.Session.getDefaultInstance(configuration, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication((String) configuration.getProperty("mail.filmtit.address"), (String) configuration.getProperty("mail.filmtit.password")); } }); session.setDebug(true); javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(session); try { message.addRecipient(Message.RecipientType.TO, new InternetAddress(this.email)); message.setFrom(new InternetAddress((String) configuration.getProperty("mail.filmtit.address"))); message.setSubject(this.subject); message.setText(this.message); Transport transportSSL = session.getTransport(); transportSSL.connect((String) configuration.getProperty("mail.smtps.host"), Integer.parseInt(configuration.getProperty("mail.smtps.port")), (String) configuration.getProperty("mail.filmtit.address"), (String) configuration.getProperty("mail.filmtit.password")); // account used transportSSL.sendMessage(message, message.getAllRecipients()); transportSSL.close(); } catch (MessagingException ex) { logger.error("Emailer", "An error while sending an email. " + ex); } return true; } logger.warning("Emailer", "Emailer has not collected all data to be able to send an email."); return false; }
From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java
@Override public void sendNotification(String smtpSender, String replyTo, String recipient, String subject, String htmlContent, String inReplyTo, String references) throws SendFailedException { if (smtpServer.equals("")) { logger.warn("Mail notifications are disabled."); return;// w ww . j av a 2s . com } // get the mail session Session session = getMailSession(); // Define message MimeMessage messageMim = new MimeMessage(session); try { messageMim.setFrom(new InternetAddress(smtpSender)); if (replyTo != null) { InternetAddress reply[] = new InternetAddress[1]; reply[0] = new InternetAddress(replyTo); messageMim.setReplyTo(reply); } messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); if (inReplyTo != null && inReplyTo != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(inReplyTo)) { messageMim.setHeader("In-Reply-To", inReplyTo); } } if (references != null && references != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(references)) { messageMim.setHeader("References", references); } } messageMim.setSubject(subject, charset); // Create a "related" Multipart message // content type is multipart/alternative // it will contain two part BodyPart 1 and 2 Multipart mp = new MimeMultipart("alternative"); // BodyPart 2 // content type is multipart/related // A multipart/related is used to indicate that message parts should // not be considered individually but rather // as parts of an aggregate whole. The message consists of a root // part (by default, the first) which reference other parts inline, // which may in turn reference other parts. Multipart html_mp = new MimeMultipart("related"); // Include an HTML message with images. // BodyParts: the HTML file and an image // Get the HTML file BodyPart rel_bph = new MimeBodyPart(); rel_bph.setDataHandler( new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset))); html_mp.addBodyPart(rel_bph); // Create the second BodyPart of the multipart/alternative, // set its content to the html multipart, and add the // second bodypart to the main multipart. BodyPart alt_bp2 = new MimeBodyPart(); alt_bp2.setContent(html_mp); mp.addBodyPart(alt_bp2); messageMim.setContent(mp); // RFC 822 "Date" header field // Indicates that the message is complete and ready for delivery messageMim.setSentDate(new GregorianCalendar().getTime()); // Since we used html tags, the content must be marker as text/html // messageMim.setContent(content,"text/html; charset="+charset); Transport tr = session.getTransport("smtp"); // Connect to smtp server, if needed if (needsAuth) { tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword); messageMim.saveChanges(); tr.sendMessage(messageMim, messageMim.getAllRecipients()); tr.close(); } else { // Send message Transport.send(messageMim); } } catch (SendFailedException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient, e); throw e; } catch (MessagingException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } catch (Exception e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } }
From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java
/** * This is the actual java mail execution. * * @param notification//from w ww. j ava 2 s . c o m */ 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:com.whizzosoftware.hobson.bootstrap.api.hub.OSGIHubManager.java
protected void sendEmail(EmailConfiguration config, String recipientAddress, String subject, String body) { String mailHost = config.getMailServer(); Boolean mailUseSMTPS = config.isSMTPS(); String mailUser = config.getUsername(); String mailPassword = config.getPassword(); if (mailHost == null) { throw new HobsonRuntimeException("No mail host is configured; unable to execute e-mail action"); } else if (mailUseSMTPS && mailUser == null) { throw new HobsonRuntimeException( "No mail server username is configured for SMTPS; unable to execute e-mail action"); } else if (mailUseSMTPS && mailPassword == null) { throw new HobsonRuntimeException( "No mail server password is configured for SMTPS; unable to execute e-mail action"); }/*from w w w . j av a 2 s. c o m*/ // create mail session Properties props = new Properties(); props.put("mail.smtp.host", mailHost); Session session = Session.getDefaultInstance(props, null); // create the mail message Message msg = createMessage(session, config, recipientAddress, subject, body); // send the message String protocol = mailUseSMTPS ? "smtps" : "smtp"; int port = mailUseSMTPS ? 465 : 25; try { Transport transport = session.getTransport(protocol); logger.debug("Sending e-mail to {} using {}@{}:{}", msg.getAllRecipients(), mailUser, mailHost, port); transport.connect(mailHost, port, mailUser, mailPassword); msg.saveChanges(); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); logger.debug("Message sent successfully"); } catch (MessagingException e) { logger.error("Error sending e-mail message", e); throw new HobsonRuntimeException("Error sending e-mail message", e); } }
From source file:com.gcrm.util.mail.MailService.java
public void sendSimpleMail(String toAddress) throws Exception { List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName()); EmailSetting emailSetting = null;/*w w w . j a va2 s. c o m*/ if (emailSettings != null && emailSettings.size() > 0) { emailSetting = emailSettings.get(0); } else { return; } Session mailSession = this.createSmtpSession(emailSetting); if (mailSession != null) { Transport transport = mailSession.getTransport(); MimeMessage msg = new MimeMessage(mailSession); MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8"); helper.setFrom(emailSetting.getFrom_address()); helper.setTo(toAddress); helper.setSubject("Test Mail From " + emailSetting.getFrom_name()); helper.setText("This is test mail from " + emailSetting.getFrom_name(), true); transport.connect(); transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO)); } }
From source file:at.gv.egovernment.moa.id.configuration.helper.MailHelper.java
private static void sendMail(ConfigurationProvider config, String subject, String recipient, String content) throws ConfigurationException { try {//from w ww .j a va 2 s . c om log.debug("Sending mail."); MiscUtil.assertNotNull(subject, "subject"); MiscUtil.assertNotNull(recipient, "recipient"); MiscUtil.assertNotNull(content, "content"); Properties props = new Properties(); props.setProperty("mail.transport.protocol", "smtp"); props.setProperty("mail.host", config.getSMTPMailHost()); log.trace("Mail host: " + config.getSMTPMailHost()); if (config.getSMTPMailPort() != null) { log.trace("Mail port: " + config.getSMTPMailPort()); props.setProperty("mail.port", config.getSMTPMailPort()); } if (config.getSMTPMailUsername() != null) { log.trace("Mail user: " + config.getSMTPMailUsername()); props.setProperty("mail.user", config.getSMTPMailUsername()); } if (config.getSMTPMailPassword() != null) { log.trace("Mail password: " + config.getSMTPMailPassword()); props.setProperty("mail.password", config.getSMTPMailPassword()); } Session mailSession = Session.getDefaultInstance(props, null); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); message.setSubject(subject); log.trace("Mail from: " + config.getMailFromName() + "/" + config.getMailFromAddress()); message.setFrom(new InternetAddress(config.getMailFromAddress(), config.getMailFromName())); log.trace("Recipient: " + recipient); message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient)); log.trace("Creating multipart content of mail."); MimeMultipart multipart = new MimeMultipart("related"); log.trace("Adding first part (html)"); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=ISO-8859-15"); multipart.addBodyPart(messageBodyPart); // log.trace("Adding mail images"); // messageBodyPart = new MimeBodyPart(); // for (Image image : images) { // messageBodyPart.setDataHandler(new DataHandler(image)); // messageBodyPart.setHeader("Content-ID", "<" + image.getContentId() + ">"); // multipart.addBodyPart(messageBodyPart); // } message.setContent(multipart); transport.connect(); log.trace("Sending mail message."); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); log.trace("Successfully sent."); transport.close(); } catch (MessagingException e) { throw new ConfigurationException(e); } catch (UnsupportedEncodingException e) { throw new ConfigurationException(e); } }