List of usage examples for javax.mail.internet MimeMessage getAllRecipients
@Override public Address[] getAllRecipients() throws MessagingException
From source file:bean.RedSocial.java
/** * /*from w ww . j a va 2s . com*/ * @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.github.thorqin.toolkit.mail.MailService.java
private void sendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); final Session session; props.put("mail.smtp.auth", String.valueOf(setting.auth)); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", setting.host); props.put("mail.smtp.port", setting.port); if (setting.secure.equals(SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); } else if (setting.secure.equals(SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", setting.port); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); }//from w w w.j a v a 2s .c om if (!setting.auth) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(setting.user, setting.password); } }); if (setting.debug) session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (setting.from != null) message.setFrom(new InternetAddress(setting.from)); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (setting.trace && tracer != null) { Tracer.Info info = new Tracer.Info(); info.catalog = "mail"; info.name = "send"; info.put("sender", StringUtils.join(message.getFrom())); info.put("recipients", mail.to); info.put("SMTPServer", setting.host); info.put("SMTPAccount", setting.user); info.put("subject", mail.subject); info.put("startTime", beginTime); info.put("runningTime", System.currentTimeMillis() - beginTime); tracer.trace(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java
@Override public Message sendMail(AppockMail appockMail) throws MessagingException { if (CollectionUtils.isEmpty(appockMail.getListeDestinataire())) { log.warn("Mail non envoy, liste des destinataires vide : " + appockMail); return null; }/*from w ww.j av a2 s.c om*/ MimeMessage msg = new MimeMessage(mailServer); msg.setFrom(appockMail.getFrom() != null ? appockMail.getFrom() : defaultFrom()); String prefixeSujet = isModeProduction() ? "" : "[TEST APPOCK] "; msg.setSubject(prefixeSujet + appockMail.getSujet(), configService.getEncodageSujetEmail()); StringBuilder infoAdditionnelle = new StringBuilder(); for (InternetAddress adresse : appockMail.getListeDestinataire()) { if (isModeProduction()) { // on est en production, envoi rel de mail au destinataire msg.addRecipient(Message.RecipientType.TO, adresse); } else { // en test, on envoie le mail la personne connecte InternetAddress adresseTesteur = getAdresseMailDestinataireTesteur(); if (adresseTesteur != null) { msg.addRecipient(Message.RecipientType.TO, adresseTesteur); } List<String> listeAdresseMail = new ArrayList<>(); for (InternetAddress internetAddress : appockMail.getListeDestinataire()) { listeAdresseMail.add(internetAddress.getAddress()); } infoAdditionnelle.append("En production cet email serait envoy vers ") .append(StringUtils.join(listeAdresseMail, ", ")).append("<br/><hr/>"); break; } } String contenuFinal = ""; if (!StringUtils.isBlank(infoAdditionnelle.toString())) { contenuFinal += "<font face=\"arial\" >" + infoAdditionnelle.toString() + "</font>"; } contenuFinal += "<font face=\"arial\" >" + appockMail.getContenu() + "<br/><br/></font>" + configService.getPiedDeMail(); gereBonLivraisonDansMail(appockMail, msg, contenuFinal); if (!ArrayUtils.isEmpty(msg.getAllRecipients())) { Transport.send(msg); } return msg; }
From source file:com.github.thorqin.webapi.mail.MailService.java
private void doSendMail(Mail mail) { long beginTime = System.currentTimeMillis(); Properties props = new Properties(); Session session;/*from w ww . j a va 2s .c om*/ props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication())); // If want to display SMTP protocol detail then uncomment following statement // props.put("mail.debug", "true"); props.put("mail.smtp.host", serverConfig.getHost()); if (serverConfig.getPort() != null) { props.put("mail.smtp.port", serverConfig.getPort()); } if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) { props.put("mail.smtp.starttls.enable", "true"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) { props.put("mail.smtp.socketFactory.port", serverConfig.getPort()); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.put("mail.smtp.socketFactory.fallback", "false"); if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } else { if (!serverConfig.useAuthentication()) session = Session.getInstance(props); else session = Session.getInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword()); } }); } // Uncomment to show SMTP protocal // session.setDebug(true); MimeMessage message = new MimeMessage(session); StringBuilder mailTo = new StringBuilder(); try { if (mail.from != null) message.setFrom(new InternetAddress(mail.from)); else if (serverConfig.getFrom() != null) message.setFrom(new InternetAddress(serverConfig.getFrom())); if (mail.to != null) { for (String to : mail.to) { if (mailTo.length() > 0) mailTo.append(","); mailTo.append(to); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); } } if (mail.subject != null) message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?="); message.setSentDate(new Date()); BodyPart bodyPart = new MimeBodyPart(); if (mail.htmlBody != null) bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8"); else if (mail.textBody != null) bodyPart.setText(mail.textBody); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(bodyPart); if (mail.attachments != null) { for (String attachment : mail.attachments) { BodyPart attachedBody = new MimeBodyPart(); File attachedFile = new File(attachment); DataSource source = new FileDataSource(attachedFile); attachedBody.setDataHandler(new DataHandler(source)); attachedBody.setDisposition(MimeBodyPart.ATTACHMENT); String filename = attachedFile.getName(); attachedBody.setFileName( "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?="); multipart.addBodyPart(attachedBody); } } message.setContent(multipart); message.saveChanges(); Transport transport = session.getTransport("smtp"); transport.connect(); transport.sendMessage(message, message.getAllRecipients()); transport.close(); if (serverConfig.enableTrace()) { MailInfo info = new MailInfo(); info.recipients = mail.to; info.sender = StringUtil.join(message.getFrom()); info.smtpServer = serverConfig.getHost(); info.smtpUser = serverConfig.getUsername(); info.subject = mail.subject; info.startTime = beginTime; info.runningTime = System.currentTimeMillis() - beginTime; MonitorService.record(info); } } catch (Exception ex) { logger.log(Level.SEVERE, "Send mail failed!", ex); } }
From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java
private void createAndSendMessage(Transport transport, String subject, String text, String nameFrom, String emailFrom, Emails emails, String ip) { // Assuming you are sending email from localhost String host = ConfigManager.getInstance().getSmtpMailhost(); String port = ConfigManager.getInstance().getSmtpMailport(); String password = ConfigManager.getInstance().getSmtpMailpassword(); String auth = ConfigManager.getInstance().getSmtpMailauth(); String sender = ConfigManager.getInstance().getSmtpMailuser(); // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.starttls.enable", "true"); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.smtp.user", sender); properties.setProperty("mail.smtp.password", password); properties.setProperty("mail.smtp.auth", auth); properties.setProperty("mail.smtp.port", port); javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties); // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. if (!StringUtils.isBlank(sender)) { try {/* w ww. j ava 2s .c om*/ message.setFrom(new InternetAddress(sender)); } catch (AddressException ex) { logger.log(Level.SEVERE, "Sender address is not a valid mail address" + sender, ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Sender: " + sender + " due to", ex); } } List<Address> addresses = new ArrayList<Address>(); String receivers = emails.getReceivers(); receivers = StringUtils.trim(receivers); for (String receiver : receivers.split(";")) { if (!StringUtils.isBlank(receiver)) { try { addresses.add(new InternetAddress(receiver)); } catch (AddressException ex) { logger.log(Level.SEVERE, "Receiver address is not a valid mail address" + receiver, ex); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Receiver: " + receiver + " due to", ex); } } } Address[] add = new Address[addresses.size()]; addresses.toArray(add); try { message.addRecipients(Message.RecipientType.TO, add); // Set Subject: header field message.setSubject("[Pundit Contact Form]: " + subject); // Now set the actual message message.setText("Subject: " + subject + " \n" + "From: " + nameFrom + " (email: " + emailFrom + ") \n" + "Date: " + new Date() + "\n" + "IP: " + ip + "\n" + "Text: \n" + text); } catch (MessagingException ex) { logger.log(Level.SEVERE, "Can't create message for Recipient: " + add + " due to", ex); } // Send message try { logger.log(Level.INFO, "Trying to send message to receivers: {0}", Arrays.toString(message.getAllRecipients())); transport = session.getTransport("smtp"); transport.connect(host, sender, password); transport.sendMessage(message, message.getAllRecipients()); logger.log(Level.INFO, "Sent messages to all receivers {0}", Arrays.toString(message.getAllRecipients())); } catch (NoSuchProviderException nspe) { logger.log(Level.SEVERE, "Cannot find smtp provider", nspe); } catch (MessagingException me) { logger.log(Level.SEVERE, "Cannot set transport layer ", me); } finally { try { transport.close(); } catch (MessagingException ex) { } catch (NullPointerException ne) { } } }
From source file:edu.ku.brc.helpers.EMailHelper.java
/** * Send an email. Also sends it as a gmail if applicable, and does password checking. * @param host host of SMTP server/*from www .j a v a 2 s . c o m*/ * @param uName username of email account * @param pWord password of email account * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email * @param toEMailAddr the email addr of who this is going to * @param subject the Textual subject line of the email * @param bodyText the body text of the email (plain text???) * @param fileAttachment and optional file to be attached to the email * @return true if the msg was sent, false if not */ public static ErrorType sendMsg(final String host, final String uName, final String pWord, final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText, final String mimeType, final String port, final String security, final File fileAttachment) { String userName = uName; String password = pWord; if (StringUtils.isEmpty(toEMailAddr)) { UIRegistry.showLocalizedError("EMailHelper.NO_TO_ERR"); return ErrorType.Error; } if (StringUtils.isEmpty(fromEMailAddr)) { UIRegistry.showLocalizedError("EMailHelper.NO_FROM_ERR"); return ErrorType.Error; } //if (isGmailEmail()) //{ // return sendMsgAsGMail(host, userName, password, fromEMailAddr, toEMailAddr, subject, bodyText, mimeType, port, security, fileAttachment); //} Boolean fail = false; ArrayList<String> userAndPass = new ArrayList<String>(); boolean isSSL = security.equals("SSL"); String[] keys = { "mail.smtp.host", "mail.smtp.port", "mail.smtp.auth", "mail.smtp.starttls.enable", "mail.smtp.socketFactory.port", "mail.smtp.socketFactory.class", "mail.smtp.socketFactory.fallback", "mail.imap.auth.plain.disable", }; Properties props = System.getProperties(); for (String key : keys) { props.remove(key); } props.put("mail.smtp.host", host); //$NON-NLS-1$ if (StringUtils.isNotEmpty(port) && StringUtils.isNumeric(port)) { props.put("mail.smtp.port", port); //$NON-NLS-1$ //$NON-NLS-2$ } else { props.remove("mail.smtp.port"); } if (StringUtils.isNotEmpty(security)) { if (security.equals("TLS")) { props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$ } else if (isSSL) { props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$ String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; props.put("mail.smtp.socketFactory.port", port); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); props.put("mail.imap.auth.plain.disable", "true"); } } Session session = null; if (isSSL) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(uName, pWord); } }); } else { session = Session.getInstance(props, null); } session.setDebug(instance.isDebugging); if (instance.isDebugging) { log.debug("Host: " + host); //$NON-NLS-1$ log.debug("UserName: " + userName); //$NON-NLS-1$ log.debug("Password: " + password); //$NON-NLS-1$ log.debug("From: " + fromEMailAddr); //$NON-NLS-1$ log.debug("To: " + toEMailAddr); //$NON-NLS-1$ log.debug("Subject: " + subject); //$NON-NLS-1$ log.debug("Port: " + port); //$NON-NLS-1$ log.debug("Security: " + security); //$NON-NLS-1$ } try { // create a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromEMailAddr)); if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$ { StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$ InternetAddress[] address = new InternetAddress[st.countTokens()]; int i = 0; while (st.hasMoreTokens()) { String toStr = st.nextToken().trim(); address[i++] = new InternetAddress(toStr); } msg.setRecipients(Message.RecipientType.TO, address); } else { try { InternetAddress[] address = { new InternetAddress(toEMailAddr) }; msg.setRecipients(Message.RecipientType.TO, address); } catch (javax.mail.internet.AddressException ex) { UIRegistry.showLocalizedError("EMailHelper.TO_ADDR_ERR", toEMailAddr); return ErrorType.Error; } } msg.setSubject(subject); //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\""); // create the second message part if (fileAttachment != null) { // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\""); //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\""); MimeBodyPart mbp2 = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileAttachment); mbp2.setDataHandler(new DataHandler(fds)); mbp2.setFileName(fds.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); } else { // add the Multipart to the message msg.setContent(bodyText, mimeType); } final int TRIES = 1; // set the Date: header msg.setSentDate(new Date()); Exception exception = null; // send the message int cnt = 0; do { cnt++; SMTPTransport t = isSSL ? null : (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$ try { if (isSSL) { Transport.send(msg); } else { t.connect(host, userName, password); t.sendMessage(msg, msg.getAllRecipients()); } fail = false; } catch (SendFailedException mex) { mex.printStackTrace(); exception = mex; } catch (MessagingException mex) { if (mex.getCause() instanceof UnknownHostException) { instance.lastErrorMsg = null; fail = true; UIRegistry.showLocalizedError("EMailHelper.UNK_HOST", host); } else if (mex.getCause() instanceof ConnectException) { instance.lastErrorMsg = null; fail = true; UIRegistry.showLocalizedError( "EMailHelper." + (StringUtils.isEmpty(port) ? "CNCT_ERR1" : "CNCT_ERR2"), port); } else { mex.printStackTrace(); exception = mex; } } catch (Exception mex) { mex.printStackTrace(); exception = mex; } finally { if (t != null) { log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$ t.close(); } } if (exception != null) { fail = true; instance.lastErrorMsg = exception.toString(); //wrong username or password, get new one if (exception.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$ { UIRegistry.showLocalizedError("EMailHelper.UP_ERROR", userName); userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow()); if (userAndPass == null) { //the user is done instance.lastErrorMsg = null; return ErrorType.Cancel; } userName = userAndPass.get(0); password = userAndPass.get(1); } } exception = null; } while (fail && cnt < TRIES); } catch (Exception mex) { //edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex); instance.lastErrorMsg = mex.toString(); mex.printStackTrace(); Exception ex = null; if (mex instanceof MessagingException && (ex = ((MessagingException) mex).getNextException()) != null) { ex.printStackTrace(); instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$ } return ErrorType.Error; } if (fail) { return ErrorType.Error; } //else return ErrorType.OK; }
From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java
public void send(Message msg) { Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); properties.setProperty("mail.transport.protocol", "smtp"); if (username != null && !username.isEmpty()) { properties.setProperty("mail.user", username); properties.setProperty("mail.password", password); }//from w ww . ja v a 2 s.c om if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } Session session = Session.getDefaultInstance(properties); MimeMessage message = new MimeMessage(session); try { message.setFrom(msg.getFrom()); if (msg.getTo().size() > 1) { List<InternetAddress> addresses = msg.getTo(); message.addRecipients(TO, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(TO, msg.getTo().get(0)); } if (msg.getBcc() != null && msg.getBcc().size() != 0) { if (msg.getTo().size() > 1) { List<InternetAddress> addresses = msg.getBcc(); message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(TO, msg.getBcc().get(0)); } } if (msg.getCc() != null && msg.getCc().size() > 0) { if (msg.getCc().size() > 1) { List<InternetAddress> addresses = msg.getCc(); message.addRecipients(CC, addresses.toArray(new Address[addresses.size()])); } else { message.addRecipient(CC, msg.getCc().get(0)); } } message.setSubject(msg.getSubject(), "UTF-8"); MimeBodyPart mbp1 = new MimeBodyPart(); // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); if (msg.getBodyType() == Message.BodyType.HTML_TEXT) { mbp1.setContent(msg.getBody(), "text/html"); } else { mbp1.setText(msg.getBody(), "UTF-8"); } if (port != null && !port.isEmpty()) { properties.setProperty("mail.smtp.port", port); } mp.addBodyPart(mbp1); if (msg.getAttachments().size() > 0) { for (String fileName : msg.getAttachments()) { // create the second message part MimeBodyPart mbpFile = new MimeBodyPart(); // attach the file to the message FileDataSource fds = new FileDataSource(fileName); mbpFile.setDataHandler(new DataHandler(fds)); mbpFile.setFileName(fds.getName()); mp.addBodyPart(mbpFile); } } // add the Multipart to the message message.setContent(mp); if (username != null && !username.isEmpty()) { properties.setProperty("mail.user", username); properties.setProperty("mail.password", password); properties.put("mail.smtp.auth", auth); properties.put("mail.smtp.starttls.enable", starttls); Transport mailTransport = session.getTransport(); mailTransport.connect(host, username, password); mailTransport.sendMessage(message, message.getAllRecipients()); } else { Transport.send(message); log.debug("Message successfully sent."); } } catch (Throwable e) { log.error("Exception while sending mail", e); } }
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 www.j a v a 2s . co 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:library.Form_Library.java
License:asdf
public void sendFromGMail(String from, String pass, String to, String subject, String body) { this.taBaoCao.append("Sent to " + to + " successfully.\n"); Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try {//from w w w . ja v a 2 s.c o m message.setFrom(new InternetAddress(from)); InternetAddress toAddress = new InternetAddress(); // To get the array of addresses // for( int i = 0; i < to.length; i++ ) { toAddress = new InternetAddress(to); // } // for( int i = 0; i < toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress); // } message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); System.out.print("Successfully Sent" + "\n"); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } }