List of usage examples for javax.mail Transport sendMessage
public abstract void sendMessage(Message msg, Address[] addresses) throws MessagingException;
From source file:com.liferay.mail.imap.IMAPAccessor.java
public void sendMessage(String personalName, String sender, Address[] to, Address[] cc, Address[] bcc, String subject, String body, List<MailFile> mailFiles) throws PortalException { Folder jxFolder = null;// w w w .ja va2 s . c om try { jxFolder = openFolder(_account.getSentFolderId()); Message jxMessage = createMessage(personalName, sender, to, cc, bcc, subject, body, mailFiles); Transport transport = _imapConnection.getTransport(); transport.sendMessage(jxMessage, jxMessage.getAllRecipients()); transport.close(); jxFolder.addMessageCountListener(new IMAPMessageCountListener(_user, _account, _password)); jxFolder.appendMessages(new Message[] { jxMessage }); } catch (MessagingException me) { throw new MailException(me); } catch (UnsupportedEncodingException uee) { throw new MailException(uee); } finally { closeFolder(jxFolder, false); } }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void sendPartially() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO 1 .sendLine("250 OK").recvLine() // RCPT TO 2 .sendLine("550 not found").recvLine() // RCPT TO 3 .sendLine("550 not found").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .sendLine("221 bye").build().start(PORT); Session session = JMSession.getSession(); session.getProperties().setProperty("mail.smtp.sendpartial", "true"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\n" + "To: rcpt1@zimbra.com, rcpt2@zimbra.com, rcpt3@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); try {/*from www .j a va2 s . co m*/ transport.sendMessage(msg, msg.getAllRecipients()); } catch (SendFailedException e) { Assert.assertEquals(1, e.getValidSentAddresses().length); Assert.assertEquals(0, e.getValidUnsentAddresses().length); Assert.assertEquals(2, e.getInvalidAddresses().length); } finally { transport.close(); } server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt1@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt2@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt3@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void nullMailFrom() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").sendLine("250 OK").recvLine() // QUIT .sendLine("221 bye").build().start(PORT); Session session = JMSession.getSession(); session.getProperties().setProperty("mail.smtp.from", "from@zimbra.com"); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; SMTPMessage msg = new SMTPMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))); msg.setEnvelopeFrom("<>"); // this should override the previously set mail.smtp.from transport.sendMessage(msg, msg.getAllRecipients()); transport.close();/* w w w . j av a 2 s . c o m*/ server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertEquals("QUIT\r\n", server.replay()); Assert.assertNull(server.replay()); }
From source file:com.gcrm.util.mail.MailService.java
public void sendHtmlMail(String from, String[] to, String subject, String text, String[] fileNames, File[] files) throws Exception { List<EmailSetting> emailSettings = baseService.getAllObjects(EmailSetting.class.getSimpleName()); EmailSetting emailSetting = null;// w w w . j a v a2s.c om if (emailSettings != null && emailSettings.size() > 0) { emailSetting = emailSettings.get(0); } else { return; } if (from == null) { from = emailSetting.getFrom_address(); } Session mailSession = createSmtpSession(emailSetting); if (mailSession != null) { Transport transport = mailSession.getTransport(); MimeMessage msg = new MimeMessage(mailSession); MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8"); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); if (fileNames != null && files != null) { String fileName = null; File file = null; for (int i = 0; i < fileNames.length; i++) { fileName = fileNames[i]; file = files[i]; if (fileName != null && file != null) { helper.addAttachment(fileName, file); } } } transport.connect(); transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO)); } }
From source file:com.cubusmail.mail.MessageHandler.java
/** * @throws MessagingException/*from www .j ava2 s . co m*/ * @throws IOException */ public void send() throws MessagingException, IOException { buildBodyContent(); this.message.setHeader("X-Mailer", CubusConstants.APPLICATION_NAME); this.message.setSentDate(new Date()); Transport transport = this.session.getTransport(); if (!transport.isConnected()) { transport.connect(); } transport.sendMessage(this.message, this.message.getAllRecipients()); transport.close(); }
From source file:bean.RedSocial.java
/** * //from w w w. j a va2 s . c o m * @param _username * @param _email * @param _password */ @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = transactionalBusinessException.ComentariosViaException.class) public void solicitarAcceso(String _username, String _email, String _password) { if (daoUsuario.obtenerUsuario(_username) != null) { throw new exceptionsBusiness.UsernameNoDisponible(); } String hash = BCrypt.hashpw(_password, BCrypt.gensalt()); Token token = new Token(_username, _email, hash); daoToken.guardarToken(token); //enviar token de acceso a la direccion email String correoEnvia = "skala2climbing@gmail.com"; String claveCorreo = "vNspLa5H"; // La configuracin para enviar correo Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.starttls.enable", "true"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); properties.put("mail.user", correoEnvia); properties.put("mail.password", claveCorreo); // Obtener la sesion Session session = Session.getInstance(properties, null); try { // Crear el cuerpo del mensaje MimeMessage mimeMessage = new MimeMessage(session); // Agregar quien enva el correo mimeMessage.setFrom(new InternetAddress(correoEnvia, "Skala2Climbing")); // Los destinatarios InternetAddress[] internetAddresses = { new InternetAddress(token.getEmail()) }; // Agregar los destinatarios al mensaje mimeMessage.setRecipients(Message.RecipientType.TO, internetAddresses); // Agregar el asunto al correo mimeMessage.setSubject("Confirmacin de registro"); // Creo la parte del mensaje MimeBodyPart mimeBodyPart = new MimeBodyPart(); String ip = "90.165.24.228"; mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: http://" + ip + ":8383/redsocialcolaborativaclientangularjs/confirmacion.html?" + "token=" + token.getToken()); //mimeBodyPart.setText("Confirme su registro pulsando en el siguiente enlace: "+"Enlace an no disponible"); // Crear el multipart para agregar la parte del mensaje anterior Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); // Agregar el multipart al cuerpo del mensaje mimeMessage.setContent(multipart); // Enviar el mensaje Transport transport = session.getTransport("smtp"); transport.connect(correoEnvia, claveCorreo); transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); transport.close(); } catch (UnsupportedEncodingException | MessagingException ex) { throw new ErrorEnvioEmail(); } }
From source file:nl.nn.adapterframework.senders.MailSender.java
protected void putOnTransport(Message msg) throws SenderException { // connect to the transport Transport transport = null; try {//w w w. j a va 2s .c om CredentialFactory cf = new CredentialFactory(getSmtpAuthAlias(), getSmtpUserid(), getSmtpPassword()); transport = session.getTransport("smtp"); transport.connect(getSmtpHost(), cf.getUsername(), cf.getPassword()); if (log.isDebugEnabled()) { log.debug("MailSender [" + getName() + "] connected transport to URL [" + transport.getURLName() + "]"); } transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } catch (Exception e) { throw new SenderException("MailSender [" + getName() + "] cannot connect send message to smtpHost [" + getSmtpHost() + "]", e); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException e1) { log.warn("MailSender [" + getName() + "] got exception closing connection", e1); } } } }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java
/** AFter all files are stored in temporary tabe takes them and sens as zip or as separate attachments * //from w ww . ja v a 2s .c om * @param mailOptions * @return */ public boolean sendFiles(Map<String, Object> mailOptions) { logger.debug("IN"); try { final String DEFAULT_SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; final String CUSTOM_SSL_FACTORY = "it.eng.spagobi.commons.services.DummySSLSocketFactory"; String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH); File tempFolder = new File(tempFolderPath); if (!tempFolder.exists() || !tempFolder.isDirectory()) { logger.error("Temp Folder " + tempFolderPath + " does not exist or is not a directory: stop sending mail"); return false; } String smtphost = null; String pass = null; String smtpssl = null; String trustedStorePath = null; String user = null; String from = null; int smtpPort = 25; try { smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpportS = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpportS + " use SSL: " + smtpssl); //Custom Trusted Store Certificate Options trustedStorePath = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.file"); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpportS == null) || smtpportS.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smtpPort = Integer.parseInt(smtpportS); } from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); } catch (Exception e) { logger.error("Some E-mail configuration not set in table sbi_config: check you have all settings.", e); throw new Exception( "Some E-mail configuration not set in table sbi_config: check you have all settings."); } String mailSubj = mailOptions.get(MAIL_SUBJECT) != null ? (String) mailOptions.get(MAIL_SUBJECT) : null; Map parametersMap = mailOptions.get(PARAMETERS_MAP) != null ? (Map) mailOptions.get(PARAMETERS_MAP) : null; mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = mailOptions.get(MAIL_TXT) != null ? (String) mailOptions.get(MAIL_TXT) : null; String[] recipients = mailOptions.get(RECIPIENTS) != null ? (String[]) mailOptions.get(RECIPIENTS) : null; //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.p ort", Integer.toString(smtpPort)); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); //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(smtpPort)); 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.getDefaultInstance(props, auth); session = Session.getInstance(props, auth); //session.setDebug(true); //session.setDebugOut(null); logger.info("Session.getInstance(props, auth)"); } else { //session = Session.getDefaultInstance(props); session = Session.getInstance(props); logger.info("Session.getInstance(props)"); } // 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 String subject = mailSubj; String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : null; Boolean reportNameInSubject = mailOptions.get(REPORT_NAME_IN_SUBJECT) != null && !mailOptions.get(REPORT_NAME_IN_SUBJECT).toString().equals("") ? (Boolean) mailOptions.get(REPORT_NAME_IN_SUBJECT) : null; //Boolean descriptionSuffix =mailOptions.get(DESCRIPTION_SUFFIX) != null && !mailOptions.get(DESCRIPTION_SUFFIX).toString().equals("")? (Boolean) mailOptions.get(DESCRIPTION_SUFFIX) : null; String zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME) : "Zipped Documents"; String contentType = mailOptions.get(CONTENT_TYPE) != null ? (String) mailOptions.get(CONTENT_TYPE) : null; String fileExtension = mailOptions.get(FILE_EXTENSION) != null ? (String) mailOptions.get(FILE_EXTENSION) : null; if (reportNameInSubject) { subject += " " + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt); // attach the file to the message boolean isZipDocument = mailOptions.get(IS_ZIP_DOCUMENT) != null ? (Boolean) mailOptions.get(IS_ZIP_DOCUMENT) : false; zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME) : "Zipped Documents"; // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); if (isZipDocument) { logger.debug("Make zip"); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2 = zipAttachment(zipFileName, mailOptions, tempFolder); mp.addBodyPart(mbp2); } else { logger.debug("Attach single files"); SchedulerDataSource sds = null; MimeBodyPart bodyPart = null; try { String[] entries = tempFolder.list(); for (int i = 0; i < entries.length; i++) { logger.debug("Attach file " + entries[i]); File f = new File(tempFolder + File.separator + entries[i]); byte[] content = getBytesFromFile(f); bodyPart = new MimeBodyPart(); sds = new SchedulerDataSource(content, contentType, entries[i]); //sds = new SchedulerDataSource(content, contentType, entries[i] + fileExtension); bodyPart.setDataHandler(new DataHandler(sds)); bodyPart.setFileName(sds.getName()); mp.addBodyPart(bodyPart); } } catch (Exception e) { logger.error("Error while attaching files", e); } } // add the Multipart to the message msg.setContent(mp); logger.debug("Preparing to send mail"); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { logger.debug("Smtps mode active user " + user); //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smtpPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { logger.debug("Smtp mode"); //Use normal SMTP Transport.send(msg); } // logger.debug("delete tempFolder path "+tempFolder.getPath()); // boolean deleted = tempFolder.delete(); // logger.debug("Temp folder deleted "+deleted); } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:org.apache.hupa.server.handler.AbstractSendMessageHandler.java
/** * Send the message using SMTP, if the configuration uses authenticated SMTP, it uses * the user stored in session to get the given login and password. * // w w w. j av a 2 s . c o m * @param user * @param session * @param message * @throws MessagingException */ protected void sendMessage(User user, Message message) throws MessagingException { Transport transport = cache.getMailTransport(useSSL); if (auth) { logger.debug("Use auth for smtp connection"); transport.connect(address, port, user.getName(), user.getPassword()); } else { transport.connect(address, port, null, null); } Address[] recips = message.getAllRecipients(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < recips.length; i++) { sb.append(recips[i]); if (i != recips.length - 1) { sb.append(", "); } } logger.info("Send message from " + message.getFrom()[0].toString() + " to " + sb.toString()); transport.sendMessage(message, recips); }
From source file:com.zimbra.cs.mailclient.smtp.SmtpTransportTest.java
@Test(timeout = 3000) public void dataException() throws Exception { server = MockTcpServer.scenario().sendLine("220 test ready").recvLine() // EHLO .sendLine("250 OK").recvLine() // MAIL FROM .sendLine("250 OK").recvLine() // RCPT TO .sendLine("250 OK").recvLine() // DATA .sendLine("354 OK").swallowUntil("\r\n.\r\n").build().start(PORT); Session session = JMSession.getSession(); Transport transport = session.getTransport("smtp"); transport.connect("localhost", PORT, null, null); String raw = "From: sender@zimbra.com\nTo: rcpt@zimbra.com\nSubject: test\n\ntest"; MimeMessage msg = new ZMimeMessage(session, new SharedByteArrayInputStream(raw.getBytes(Charsets.ISO_8859_1))) { @Override//from w w w . j a v a 2s .c om public void writeTo(OutputStream os, String[] ignoreList) throws MessagingException { throw new MessagingException(); // exception while encoding } }; try { transport.sendMessage(msg, msg.getAllRecipients()); Assert.fail(); } catch (SendFailedException expected) { } finally { transport.close(); } server.shutdown(1000); Assert.assertEquals("EHLO localhost\r\n", server.replay()); Assert.assertEquals("MAIL FROM:<sender@zimbra.com>\r\n", server.replay()); Assert.assertEquals("RCPT TO:<rcpt@zimbra.com>\r\n", server.replay()); Assert.assertEquals("DATA\r\n", server.replay()); Assert.assertNull(server.replay()); }