List of usage examples for javax.mail Transport connect
public void connect(String user, String password) throws MessagingException
From source file:com.googlecode.gmail4j.javamail.ImapGmailConnection.java
/** * Gets Gmail {@link Transport}//from w w w .ja v a 2 s . c om * * @return Configured and ready for use Transport */ public Transport getTransport() { try { final Transport transport = getSession().getTransport(); transport.addConnectionListener(new ImapConnectionHandler( new ConnectionInfo(loginCredentials.getUsername(), gmailSmtpHost, gmailSmtpPort))); transport.connect(loginCredentials.getUsername(), new String(loginCredentials.getPasword())); return transport; } catch (final Exception e) { throw new GmailException("ImapGmailClient requires ImapGmailConnection!"); } }
From source file:bean.RedSocial.java
/** * /*from w w w . j a va 2 s . c om*/ * @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:com.clustercontrol.jobmanagement.util.SendApprovalMail.java
/** * ????/*from w ww . ja v a 2 s.c o m*/ * @param toAddressStr * ?To * @param ccAddressStr * ?Cc * @param subject * ?? * @param content * * @throws MessagingException * @throws UnsupportedEncodingException */ public void sendMail(String[] toAddressStr, String[] ccAddressStr, String subject, String content) throws MessagingException, UnsupportedEncodingException { if (toAddressStr == null || toAddressStr.length <= 0) { // ?? return; } /* * https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html */ Properties _properties = new Properties(); _properties.setProperty("mail.debug", Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false))); _properties.setProperty("mail.store.protocol", HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3")); String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp"); _properties.setProperty("mail.transport.protocol", protocol); _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault()); _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault()); setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".connectiontimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.login.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.plain.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.authorizationid", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socketFactory.fallback", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".starttls.required", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING); /** * ?DB?? */ String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody"); String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password"); String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com"); String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name", "Hinemos Admin"); _fromPersonalName = convertNativeToAscii(_fromPersonalName); String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address", "admin@hinemos.com"); String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name", "Hinemos Admin"); _replyToPersonalName = convertNativeToAscii(_replyToPersonalName); String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address", "admin@hinemos.com"); int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1)) .intValue(); int _transportTriesInterval = HinemosPropertyUtil .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue(); String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address", _charsetAddressDefault); String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject", _charsetSubjectDefault); String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content", _charsetContentDefault); m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = " + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":" + _charsetSubject + ":" + _charsetContent + "]"); // JavaMail Session Session session = Session.getInstance(_properties); Message mineMsg = new MimeMessage(session); // ????? if (_fromAddress != null && _fromPersonalName != null) { mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress)); } else if (_fromAddress != null && _fromPersonalName == null) { mineMsg.setFrom(new InternetAddress(_fromAddress)); } // REPLY-TO if (_replyToAddress != null && _replyToPersonalName != null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } else if (_replyToAddress != null && _replyToPersonalName == null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } // ERRORS-TO if (_errorsToAddress != null) { mineMsg.setHeader("Errors-To", _errorsToAddress); } // ? // TO InternetAddress[] toAddress = this.getAddress(toAddressStr); if (toAddress != null && toAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); } else { return; // TO? } // CC if (ccAddressStr != null) { InternetAddress[] ccAddress = this.getAddress(ccAddressStr); if (ccAddress != null && ccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress); } } String message = "TO=" + Arrays.asList(toAddressStr); if (ccAddressStr != null) { message += ", CC=" + Arrays.asList(ccAddressStr); } m_log.debug(message); // ??? mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B")); // ? mineMsg.setContent(content, "text/plain; charset=" + _charsetContent); // ? mineMsg.setSentDate(HinemosTime.getDateInstance()); // ???true?????? for (int i = 0; i < _transportTries; i++) { Transport transport = null; try { // ? transport = session.getTransport(); boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false); if (flag) { transport.connect(_loginUser, _loginPassword); } else { transport.connect(); } transport.sendMessage(mineMsg, mineMsg.getAllRecipients()); break; } catch (AuthenticationFailedException e) { throw e; } catch (SMTPAddressFailedException e) { throw e; } catch (MessagingException me) { //_transportTries?sleep??? if (i < (_transportTries - 1)) { m_log.info("sendMail() : retry sendmail. " + me.getMessage()); try { Thread.sleep(_transportTriesInterval); } catch (InterruptedException e) { } //_transportTries??INTERNAL????Exceptionthrow } else { throw me; } } finally { if (transport != null) { transport.close(); } } } }
From source file:com.clustercontrol.notify.util.SendMail.java
public void sendMail(String[] toAddressStr, String[] ccAddressStr, String[] bccAddressStr, String subject, String content) throws MessagingException, UnsupportedEncodingException { if (toAddressStr == null || toAddressStr.length <= 0) { // ??//from w w w. j av a 2s .c om return; } /* * https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html */ Properties _properties = new Properties(); _properties.setProperty("mail.debug", Boolean.toString(HinemosPropertyUtil.getHinemosPropertyBool("mail.debug", false))); _properties.setProperty("mail.store.protocol", HinemosPropertyUtil.getHinemosPropertyStr("mail.store.protocol", "pop3")); String protocol = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.protocol", "smtp"); _properties.setProperty("mail.transport.protocol", protocol); _properties.put("mail.smtp.socketFactory", javax.net.SocketFactory.getDefault()); _properties.put("mail.smtp.ssl.socketFactory", javax.net.ssl.SSLSocketFactory.getDefault()); setProperties(_properties, "mail." + protocol + ".user", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".connectiontimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".timeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".writetimeout", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".from", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localhost", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localaddress", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".localport", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".ehlo", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.login.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.plain.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.digest-md5.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.disable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".auth.ntlm.domain", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".auth.ntlm.flags", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".submitter", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.notify", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".dsn.ret", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".allow8bitmime", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sendpartial", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".sasl.mechanisms", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.authorizationid", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.realm", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".sasl.usecanonicalhostname", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".quitwait", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".reportsuccess", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socketFactory.fallback", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail." + protocol + ".starttls.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".starttls.required", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".socks.host", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".socks.port", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".mailextension", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail." + protocol + ".userset", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail." + protocol + ".noop.strict", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.enable", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.checkserveridentity", HinemosPropertyTypeConstant.TYPE_TRUTH); setProperties(_properties, "mail.smtp.ssl.trust", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.class", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.socketFactory.port", HinemosPropertyTypeConstant.TYPE_NUMERIC); setProperties(_properties, "mail.smtp.ssl.protocols", HinemosPropertyTypeConstant.TYPE_STRING); setProperties(_properties, "mail.smtp.ssl.ciphersuites", HinemosPropertyTypeConstant.TYPE_STRING); /** * ?DB?? */ String _loginUser = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.user", "nobody"); String _loginPassword = HinemosPropertyUtil.getHinemosPropertyStr("mail.transport.password", "password"); String _fromAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.address", "admin@hinemos.com"); String _fromPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.from.personal.name", "Hinemos Admin"); _fromPersonalName = convertNativeToAscii(_fromPersonalName); String _replyToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.to.address", "admin@hinemos.com"); String _replyToPersonalName = HinemosPropertyUtil.getHinemosPropertyStr("mail.reply.personal.name", "Hinemos Admin"); _replyToPersonalName = convertNativeToAscii(_replyToPersonalName); String _errorsToAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.errors.to.address", "admin@hinemos.com"); int _transportTries = HinemosPropertyUtil.getHinemosPropertyNum("mail.transport.tries", Long.valueOf(1)) .intValue(); int _transportTriesInterval = HinemosPropertyUtil .getHinemosPropertyNum("mail.transport.tries.interval", Long.valueOf(10000)).intValue(); String _charsetAddress = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.address", _charsetAddressDefault); String _charsetSubject = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.subject", _charsetSubjectDefault); String _charsetContent = HinemosPropertyUtil.getHinemosPropertyStr("mail.charset.content", _charsetContentDefault); m_log.debug("initialized mail sender : from_address = " + _fromAddress + ", From = " + _fromPersonalName + " <" + _replyToAddress + ">" + ", Reply-To = " + _replyToPersonalName + " <" + _replyToAddress + ">" + ", Errors-To = " + _errorsToAddress + ", tries = " + _transportTries + ", tries-interval = " + _transportTriesInterval + ", Charset [address:subject:content] = [" + _charsetAddress + ":" + _charsetSubject + ":" + _charsetContent + "]"); // JavaMail Session Session session = Session.getInstance(_properties); Message mineMsg = new MimeMessage(session); // ????? if (_fromAddress != null && _fromPersonalName != null) { mineMsg.setFrom(new InternetAddress(_fromAddress, _fromPersonalName, _charsetAddress)); } else if (_fromAddress != null && _fromPersonalName == null) { mineMsg.setFrom(new InternetAddress(_fromAddress)); } // REPLY-TO if (_replyToAddress != null && _replyToPersonalName != null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress, _replyToPersonalName, _charsetAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } else if (_replyToAddress != null && _replyToPersonalName == null) { InternetAddress reply[] = { new InternetAddress(_replyToAddress) }; mineMsg.setReplyTo(reply); mineMsg.reply(true); } // ERRORS-TO if (_errorsToAddress != null) { mineMsg.setHeader("Errors-To", _errorsToAddress); } // ? // TO InternetAddress[] toAddress = this.getAddress(toAddressStr); if (toAddress != null && toAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.TO, toAddress); } else { return; // TO? } // CC if (ccAddressStr != null) { InternetAddress[] ccAddress = this.getAddress(ccAddressStr); if (ccAddress != null && ccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.CC, ccAddress); } } // BCC if (bccAddressStr != null) { InternetAddress[] bccAddress = this.getAddress(bccAddressStr); if (bccAddress != null && bccAddress.length > 0) { mineMsg.setRecipients(javax.mail.Message.RecipientType.BCC, bccAddress); } } String message = "TO=" + Arrays.asList(toAddressStr); if (ccAddressStr != null) { message += ", CC=" + Arrays.asList(ccAddressStr); } if (bccAddressStr != null) { message += ", BCC=" + Arrays.asList(bccAddressStr); } m_log.debug(message); // ??? mineMsg.setSubject(MimeUtility.encodeText(subject, _charsetSubject, "B")); // ? mineMsg.setContent(content, "text/plain; charset=" + _charsetContent); // ? mineMsg.setSentDate(HinemosTime.getDateInstance()); // ???true?????? for (int i = 0; i < _transportTries; i++) { Transport transport = null; try { // ? transport = session.getTransport(); boolean flag = HinemosPropertyUtil.getHinemosPropertyBool("mail." + protocol + ".auth", false); if (flag) { transport.connect(_loginUser, _loginPassword); } else { transport.connect(); } transport.sendMessage(mineMsg, mineMsg.getAllRecipients()); break; } catch (AuthenticationFailedException e) { throw e; } catch (SMTPAddressFailedException e) { throw e; } catch (MessagingException me) { //_transportTries?sleep??? if (i < (_transportTries - 1)) { m_log.info("sendMail() : retry sendmail. " + me.getMessage()); try { Thread.sleep(_transportTriesInterval); } catch (InterruptedException e) { } //_transportTries??INTERNAL????Exceptionthrow } else { throw me; } } finally { if (transport != null) { transport.close(); } } } }
From source file:com.autentia.tnt.mail.DefaultMailService.java
public void sendFiles(String to, String subject, String text, Collection<File> attachments) throws MessagingException { MimeMessage message = new MimeMessage(session); Transport t = session.getTransport("smtp"); message.setFrom(new InternetAddress(configurationUtil.getMailUsername())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject);/*from w w w . j a va2s . co m*/ message.setSentDate(new Date()); if (attachments == null || attachments.size() < 1) { message.setText(text); } else { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(text); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); for (File attachment : attachments) { messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachment); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachment.getName()); multipart.addBodyPart(messageBodyPart); } message.setContent(multipart); } t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword()); t.sendMessage(message, message.getAllRecipients()); t.close(); }
From source file:org.exist.xquery.modules.mail.SendEmailFunction.java
public Sequence sendEmail(Sequence[] args, Sequence contextSequence) throws XPathException { // was a session handle specified? if (args[0].isEmpty()) { throw (new XPathException(this, "Session handle not specified")); }//from ww w . j a v a 2s. c om // get the Session long sessionHandle = ((IntegerValue) args[0].itemAt(0)).getLong(); Session session = MailModule.retrieveSession(context, sessionHandle); if (session == null) { throw (new XPathException(this, "Invalid Session handle specified")); } try { List<Message> messages = parseInputEmails(session, args[1]); String proto = session.getProperty("mail.transport.protocol"); if (proto == null) proto = "smtp"; Transport t = session.getTransport(proto); try { if (session.getProperty("mail." + proto + ".auth") != null) t.connect(session.getProperty("mail." + proto + ".user"), session.getProperty("mail." + proto + ".password")); for (Message msg : messages) { t.sendMessage(msg, msg.getAllRecipients()); } } finally { t.close(); } return (Sequence.EMPTY_SEQUENCE); } catch (TransformerException te) { throw new XPathException(this, "Could not Transform XHTML Message Body: " + te.getMessage(), te); } catch (MessagingException smtpe) { throw new XPathException(this, "Could not send message(s): " + smtpe.getMessage(), smtpe); } catch (IOException ioe) { throw new XPathException(this, "Attachment in some message could not be prepared: " + ioe.getMessage(), ioe); } catch (Throwable t) { throw new XPathException(this, "Unexpected error from JavaMail layer (Is your message well structured?): " + t.getMessage(), t); } }
From source file:org.xwiki.commons.internal.DefaultMailSender.java
@Override public int send(Mail mail) { Session session = null;//from w ww .j ava 2 s. co m Transport transport = null; if ((mail.getTo() == null || StringUtils.isEmpty(mail.getTo())) && (mail.getCc() == null || StringUtils.isEmpty(mail.getCc())) && (mail.getBcc() == null || StringUtils.isEmpty(mail.getBcc()))) { logger.error("This mail has no recipient"); return 0; } if (mail.getContents().size() == 0) { logger.error("This mail is empty. You should add a content"); return 0; } try { if ((transport == null) || (session == null)) { logger.info("Sending mail : Initializing properties"); Properties props = initProperties(); session = Session.getInstance(props, null); transport = session.getTransport("smtp"); if (session.getProperty("mail.smtp.auth") == "true") transport.connect(session.getProperty("mail.smtp.server.username"), session.getProperty("mail.smtp.server.password")); else transport.connect(); try { Multipart wrapper = generateMimeMultipart(mail); InternetAddress[] adressesTo = this.toInternetAddresses(mail.getTo()); MimeMessage message = new MimeMessage(session); message.setSentDate(new Date()); message.setSubject(mail.getSubject()); message.setFrom(new InternetAddress(mail.getFrom())); message.setRecipients(javax.mail.Message.RecipientType.TO, adressesTo); if (mail.getReplyTo() != null && !StringUtils.isEmpty(mail.getReplyTo())) { logger.info("Adding ReplyTo field"); InternetAddress[] adressesReplyTo = this.toInternetAddresses(mail.getReplyTo()); if (adressesReplyTo.length != 0) message.setReplyTo(adressesReplyTo); } if (mail.getCc() != null && !StringUtils.isEmpty(mail.getCc())) { logger.info("Adding Cc recipients"); InternetAddress[] adressesCc = this.toInternetAddresses(mail.getCc()); if (adressesCc.length != 0) message.setRecipients(javax.mail.Message.RecipientType.CC, adressesCc); } if (mail.getBcc() != null && !StringUtils.isEmpty(mail.getBcc())) { InternetAddress[] adressesBcc = this.toInternetAddresses(mail.getBcc()); if (adressesBcc.length != 0) message.setRecipients(javax.mail.Message.RecipientType.BCC, adressesBcc); } message.setContent(wrapper); message.setSentDate(new Date()); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (SendFailedException sfex) { logger.error("Error encountered while trying to send the mail"); logger.error("SendFailedException has occured.", sfex); try { transport.close(); } catch (MessagingException Mex) { logger.error("MessagingException has occured.", Mex); } return 0; } catch (MessagingException mex) { logger.error("Error encountered while trying to send the mail"); logger.error("MessagingException has occured.", mex); try { transport.close(); } catch (MessagingException ex) { logger.error("MessagingException has occured.", ex); } return 0; } } } catch (Exception e) { System.out.println(e.toString()); logger.error("Error encountered while trying to setup mail properties"); try { if (transport != null) { transport.close(); } } catch (MessagingException ex) { logger.error("MessagingException has occured.", ex); } return 0; } return 1; }
From source file:org.projectforge.mail.SendMail.java
private void sendIt(final Mail composedMessage) { final Session session = Session.getInstance(properties); Transport transport = null; try {/*from w ww . j a v a2s .c o m*/ MimeMessage message = new MimeMessage(session); if (composedMessage.getFrom() != null) { message.setFrom(new InternetAddress(composedMessage.getFrom())); } else { message.setFrom(); } message.setRecipients(Message.RecipientType.TO, composedMessage.getTo()); String subject; subject = composedMessage.getSubject(); /* * try { subject = MimeUtility.encodeText(composedMessage.getSubject()); } catch (UnsupportedEncodingException ex) { * log.error("Exception encountered while encoding subject." + ex, ex); subject = composedMessage.getSubject(); } */ message.setSubject(subject, sendMailConfig.getCharset()); message.setSentDate(new Date()); if (composedMessage.getContentType() != null) { message.setText(composedMessage.getContent(), composedMessage.getCharset(), composedMessage.getContentType()); } else { message.setText(composedMessage.getContent(), sendMailConfig.getCharset()); } message.saveChanges(); // don't forget this transport = session.getTransport(); if (StringUtils.isNotEmpty(sendMailConfig.getUser()) == true) { transport.connect(sendMailConfig.getUser(), sendMailConfig.getPassword()); } else { transport.connect(); } transport.sendMessage(message, message.getAllRecipients()); } catch (MessagingException ex) { log.error("While creating and sending message: " + composedMessage.toString(), ex); throw new InternalErrorException("mail.error.exception"); } finally { if (transport != null) { try { transport.close(); } catch (MessagingException ex) { log.error("While creating and sending message: " + composedMessage.toString(), ex); throw new InternalErrorException("mail.error.exception"); } } } log.info("E-Mail successfully sent: " + composedMessage.toString()); }
From source file:com.autentia.tnt.mail.DefaultMailService.java
public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments) throws MessagingException { Transport t = null; try {//from w w w . ja v a 2s . c o m MimeMessage message = new MimeMessage(session); t = session.getTransport("smtp"); message.setFrom(new InternetAddress(configurationUtil.getMailUsername())); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setSentDate(new Date()); if (attachments == null || attachments.size() < 1) { message.setText(text); } else { // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(text); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); try { for (InputStream attachment : attachments.keySet()) { messageBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream"); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val } } catch (IOException e) { throw new MessagingException("cannot add an attachment to mail", e); } message.setContent(multipart); } t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword()); t.sendMessage(message, message.getAllRecipients()); } finally { if (t != null) { t.close(); } } }