List of usage examples for javax.mail Transport close
public synchronized void close() throws MessagingException
From source file:mx.uatx.tesis.managebeans.IndexMB.java
public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception { try {// w w w.j a v a2 s .c o m // 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: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;/*from ww w. j a v a 2s.c o m*/ } // 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.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 ww w . ja va 2 s.co 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: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 www . j a v a 2 s. com 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.apache.roller.weblogger.util.MailUtil.java
/** * This method is used to send a Message with a pre-defined * mime-type.//from w w w . ja v a2 s.c o m * * @param from e-mail address of sender * @param to e-mail address(es) of recipients * @param subject subject of e-mail * @param content the body of the e-mail * @param mimeType type of message, i.e. text/plain or text/html * @throws MessagingException the exception to indicate failure */ public static void sendMessage(String from, String[] to, String[] cc, String[] bcc, String subject, String content, String mimeType) throws MessagingException { MailProvider mailProvider = WebloggerStartup.getMailProvider(); if (mailProvider == null) { return; } Session session = mailProvider.getSession(); Message message = new MimeMessage(session); // n.b. any default from address is expected to be determined by caller. if (!StringUtils.isEmpty(from)) { InternetAddress sentFrom = new InternetAddress(from); message.setFrom(sentFrom); if (log.isDebugEnabled()) log.debug("e-mail from: " + sentFrom); } if (to != null) { InternetAddress[] sendTo = new InternetAddress[to.length]; for (int i = 0; i < to.length; i++) { sendTo[i] = new InternetAddress(to[i]); if (log.isDebugEnabled()) log.debug("sending e-mail to: " + to[i]); } message.setRecipients(Message.RecipientType.TO, sendTo); } if (cc != null) { InternetAddress[] copyTo = new InternetAddress[cc.length]; for (int i = 0; i < cc.length; i++) { copyTo[i] = new InternetAddress(cc[i]); if (log.isDebugEnabled()) log.debug("copying e-mail to: " + cc[i]); } message.setRecipients(Message.RecipientType.CC, copyTo); } if (bcc != null) { InternetAddress[] copyTo = new InternetAddress[bcc.length]; for (int i = 0; i < bcc.length; i++) { copyTo[i] = new InternetAddress(bcc[i]); if (log.isDebugEnabled()) log.debug("blind copying e-mail to: " + bcc[i]); } message.setRecipients(Message.RecipientType.BCC, copyTo); } message.setSubject((subject == null) ? "(no subject)" : subject); message.setContent(content, mimeType); message.setSentDate(new java.util.Date()); // First collect all the addresses together. Address[] remainingAddresses = message.getAllRecipients(); int nAddresses = remainingAddresses.length; boolean bFailedToSome = false; SendFailedException sendex = new SendFailedException("Unable to send message to some recipients"); Transport transport = mailProvider.getTransport(); // Try to send while there remain some potentially good addresses try { do { // Avoid a loop if we are stuck nAddresses = remainingAddresses.length; try { // Send to the list of remaining addresses, ignoring the addresses attached to the message transport.sendMessage(message, remainingAddresses); } catch (SendFailedException ex) { bFailedToSome = true; sendex.setNextException(ex); // Extract the remaining potentially good addresses remainingAddresses = ex.getValidUnsentAddresses(); } } while (remainingAddresses != null && remainingAddresses.length > 0 && remainingAddresses.length != nAddresses); } finally { transport.close(); } if (bFailedToSome) throw sendex; }
From source file:com.blackducksoftware.tools.commonframework.standard.email.CFEmailNotifier.java
/** * This is the actual java mail execution. * * @param notification/* w w w.java 2 s .co 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:org.orbeon.oxf.processor.EmailProcessor.java
public void start(PipelineContext pipelineContext) { try {/*from ww w . j a v a2 s . com*/ final Document dataDocument = readInputAsDOM4J(pipelineContext, INPUT_DATA); final Element messageElement = dataDocument.getRootElement(); // Get system id (will likely be null if document is generated dynamically) final LocationData locationData = (LocationData) messageElement.getData(); final String dataInputSystemId = locationData.getSystemID(); // Set SMTP host final Properties properties = new Properties(); final String testSmtpHostProperty = getPropertySet().getString(EMAIL_TEST_SMTP_HOST); if (testSmtpHostProperty != null) { // Test SMTP Host from properties overrides the local configuration properties.setProperty("mail.smtp.host", testSmtpHostProperty); } else { // Try regular config parameter and property String host = messageElement.element("smtp-host").getTextTrim(); if (host != null && !host.equals("")) { // Precedence goes to the local config parameter properties.setProperty("mail.smtp.host", host); } else { // Otherwise try to use a property host = getPropertySet().getString(EMAIL_SMTP_HOST); if (host == null) host = getPropertySet().getString(EMAIL_HOST_DEPRECATED); if (host == null) throw new OXFException("Could not find SMTP host in configuration or in properties"); properties.setProperty("mail.smtp.host", host); } } // Create session final Session session; { // Get credentials final String usernameTrimmed; final String passwordTrimmed; { final Element credentials = messageElement.element("credentials"); if (credentials != null) { final Element usernameElement = credentials.element("username"); final Element passwordElement = credentials.element("password"); usernameTrimmed = (usernameElement != null) ? usernameElement.getStringValue().trim() : null; passwordTrimmed = (passwordElement != null) ? passwordElement.getStringValue().trim() : ""; } else { usernameTrimmed = null; passwordTrimmed = null; } } // Check if credentials are supplied if (StringUtils.isNotEmpty(usernameTrimmed)) { // NOTE: A blank username doesn't trigger authentication if (logger.isInfoEnabled()) logger.info("Authentication"); // Set the auth property to true properties.setProperty("mail.smtp.auth", "true"); if (logger.isInfoEnabled()) logger.info("Username: " + usernameTrimmed); // Create an authenticator final Authenticator authenticator = new SMTPAuthenticator(usernameTrimmed, passwordTrimmed); // Create session with authenticator session = Session.getInstance(properties, authenticator); } else { if (logger.isInfoEnabled()) logger.info("No Authentication"); session = Session.getInstance(properties); } } // Create message final Message message = new MimeMessage(session); // Set From message.addFrom(createAddresses(messageElement.element("from"))); // Set To String testToProperty = getPropertySet().getString(EMAIL_TEST_TO); if (testToProperty == null) testToProperty = getPropertySet().getString(EMAIL_FORCE_TO_DEPRECATED); if (testToProperty != null) { // Test To from properties overrides local configuration message.addRecipient(Message.RecipientType.TO, new InternetAddress(testToProperty)); } else { // Regular list of To elements for (final Element toElement : Dom4jUtils.elements(messageElement, "to")) { final InternetAddress[] addresses = createAddresses(toElement); message.addRecipients(Message.RecipientType.TO, addresses); } } // Set Cc for (final Element ccElement : Dom4jUtils.elements(messageElement, "cc")) { final InternetAddress[] addresses = createAddresses(ccElement); message.addRecipients(Message.RecipientType.CC, addresses); } // Set Bcc for (final Element bccElement : Dom4jUtils.elements(messageElement, "bcc")) { final InternetAddress[] addresses = createAddresses(bccElement); message.addRecipients(Message.RecipientType.BCC, addresses); } // Set headers if any for (final Element headerElement : Dom4jUtils.elements(messageElement, "header")) { final String headerName = headerElement.element("name").getTextTrim(); final String headerValue = headerElement.element("value").getTextTrim(); // NOTE: Use encodeText() in case there are non-ASCII characters message.addHeader(headerName, MimeUtility.encodeText(headerValue, DEFAULT_CHARACTER_ENCODING, null)); } // Set the email subject // The JavaMail spec is badly written and is not clear about whether this needs to be done here. But it // seems to use the platform's default charset, which we don't want to deal with. So we preemptively encode. // The result is pure ASCII so that setSubject() will not attempt to re-encode it. message.setSubject(MimeUtility.encodeText(messageElement.element("subject").getStringValue(), DEFAULT_CHARACTER_ENCODING, null)); // Handle body final Element textElement = messageElement.element("text"); final Element bodyElement = messageElement.element("body"); if (textElement != null) { // Old deprecated mechanism (simple text body) message.setText(textElement.getStringValue()); } else if (bodyElement != null) { // New mechanism with body and parts handleBody(pipelineContext, dataInputSystemId, message, bodyElement); } else { throw new OXFException("Main text or body element not found");// TODO: location info } // Send message final Transport transport = session.getTransport("smtp"); Transport.send(message); transport.close(); } catch (Exception e) { throw new OXFException(e); } }
From source file:com.basicservice.service.MailService.java
public void sendEmail(String from, String to, String subject, String messageHtml) throws Exception { try {//w w w.java2s. c om Properties props = new Properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", smtpHost); props.put("mail.smtp.port", 587); props.put("mail.smtp.auth", "true"); Authenticator auth = new SMTPAuthenticator(); Session mailSession = Session.getDefaultInstance(props, auth); // mailSession.setDebug(true); Transport transport = mailSession.getTransport(); MimeMessage message = new MimeMessage(mailSession); Multipart multipart = new MimeMultipart("alternative"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(new String(messageHtml.getBytes("UTF8"), "ISO-8859-1"), "text/html"); multipart.addBodyPart(htmlPart); message.setContent(multipart); message.setFrom(new InternetAddress(from)); message.setSubject(subject, "UTF-8"); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); transport.connect(); transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO)); transport.close(); } catch (Exception e) { LOG.debug("Exception while sending email: ", e); throw e; } }
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 {// w w w . jav a 2 s.co m 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); } }
From source file:fsi_admin.JSmtpConn.java
private boolean sendMsg(String HOST, String USERNAME, String PASSWORD, StringBuffer msj, Session session, MimeMessage mmsg, MimeMultipart multipart) { try {//from ww w. ja va2 s.co m mmsg.setContent(multipart); // Create a transport. Transport transport = session.getTransport(); // Send the message. System.out.println(HOST + " " + USERNAME + " " + PASSWORD); transport.connect(HOST, USERNAME, PASSWORD); // Send the email. transport.sendMessage(mmsg, mmsg.getAllRecipients()); transport.close(); return true; } catch (MessagingException e) { e.printStackTrace(); msj.append("Error de Mensajeria al enviar SMTP: " + e.getMessage()); return false; } catch (Exception ex) { ex.printStackTrace(); msj.append("Error general de mensaje al enviar SMTP: " + ex.getMessage()); return false; } }