List of usage examples for org.apache.commons.mail Email setHostName
public void setHostName(final String aHostName)
From source file:com.pkrete.locationservice.endpoint.mailer.impl.EmailServiceImpl.java
/** * Sends the given EmailMessage to the recipients defined in the message. * Returns true if and only if the message was successfully sent to all the * recipients; otherwise false./*from w ww . j a v a 2 s. c o m*/ * * @param message email message to be sent * @return true if and only if the message was successfully sent to all the * recipients; otherwise false */ @Override public boolean send(EmailMessage message) { if (message == null) { logger.warn("Message cannot be null."); return false; } logger.debug("Create new \"{}\" email message.", message.getType().toString()); if (message.getRecipients().isEmpty()) { logger.info("No recipients defined. Nothing to do -> exit."); return false; } Email email = new SimpleEmail(); email.setHostName(PropertiesUtil.getProperty("mail.host")); email.setSmtpPort(this.converterService.strToInt(PropertiesUtil.getProperty("mail.port"))); email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getProperty("mail.user"), PropertiesUtil.getProperty("mail.password"))); email.setTLS(true); try { // Set from address email.setFrom(message.getFrom()); // Set subject email.setSubject(message.getSubject()); // Build message body StringBuilder body = new StringBuilder(); if (!message.getHeader().isEmpty()) { body.append(message.getHeader()).append("\n\n"); } if (!message.getMessage().isEmpty()) { body.append(message.getMessage()).append("\n\n"); } if (!message.getFooter().isEmpty()) { body.append(message.getFooter()).append("\n\n"); } if (!message.getSignature().isEmpty()) { body.append(message.getSignature()).append("\n\n"); } // Set message contents email.setMsg(body.toString()); // Add message receivers for (String recipient : message.getRecipients()) { logger.info("Add recipient \"{}\".", recipient); email.addTo(recipient); } // Send message email.send(); logger.info("Email was succesfully sent to {} recipients.", message.getRecipients().size()); } catch (Exception e) { logger.error("Failed to send \"{}\" email message.", message.getType().toString()); logger.error(e.getMessage()); return false; } return true; }
From source file:in.flipbrain.controllers.BaseController.java
protected void sendEmail(String to, String subject, String body) throws EmailException { logger.debug("Sending email to " + to + "\nSubject: " + subject + "\nMessage: " + body); if ("true".equalsIgnoreCase(getConfigValue(Constants.EM_FAKE_SEND))) return;/*from www . j a v a 2 s .c om*/ Email email = new SimpleEmail(); email.setHostName(getConfigValue("smtp.host")); email.setSmtpPort(Integer.parseUnsignedInt(getConfigValue("smtp.port"))); email.setAuthenticator( new DefaultAuthenticator(getConfigValue("smtp.user"), getConfigValue("smtp.password"))); email.setSSLOnConnect(Boolean.parseBoolean(getConfigValue("smtp.ssl"))); email.setFrom(getConfigValue("smtp.sender")); email.setSubject(subject); email.setMsg(body); email.addTo(to); email.send(); }
From source file:com.pkrete.locationservice.admin.mailer.impl.BasicEmailService.java
/** * Send an email to the given user when the user is created or the password * is modified./*w w w .j a v a2 s.c o m*/ * * @param user the receiver of the email */ @Override public void send(UserFull user) { logger.info("Create new email message."); Email email = new SimpleEmail(); email.setHostName(PropertiesUtil.getProperty("mail.host")); email.setSmtpPort(this.converterService.strToInt(PropertiesUtil.getProperty("mail.port"))); email.setAuthenticator(new DefaultAuthenticator(PropertiesUtil.getProperty("mail.user"), PropertiesUtil.getProperty("mail.password"))); email.setTLS(true); try { // Init variables String header = null; String msg = null; // Set from address email.setFrom(this.messageSource.getMessage("mail.from", null, null)); // Set message arguments Object[] args = new Object[] { user.getUsername(), user.getPasswordUi() }; // Set variables values if (user.getUpdated() == null) { // This is a new user if (logger.isDebugEnabled()) { logger.debug("The message is for a new user."); } // Set subject email.setSubject(this.messageSource.getMessage("mail.title.add", null, null)); // Set message header header = this.messageSource.getMessage("mail.header.add", null, null); // Set message content msg = this.messageSource.getMessage("mail.message.add", args, null); } else { // This is an existing user logger.debug("The message is for an existing user."); // Set subject email.setSubject(this.messageSource.getMessage("mail.title.edit", null, null)); // Get message header header = this.messageSource.getMessage("mail.header.edit", null, null); // Get message content msg = this.messageSource.getMessage("mail.message.edit", args, null); } // Get note String note = this.messageSource.getMessage("mail.note", null, null); // Get footer String footer = this.messageSource.getMessage("mail.footer", null, null); // Get signature String signature = this.messageSource.getMessage("mail.signature", null, null); // Build message body StringBuilder result = new StringBuilder(); if (!header.isEmpty()) { result.append(header).append("\n\n"); } if (!msg.isEmpty()) { result.append(msg).append("\n\n"); } if (!note.isEmpty()) { result.append(note).append("\n\n"); } if (!footer.isEmpty()) { result.append(footer).append("\n\n"); } if (!signature.isEmpty()) { result.append(signature).append("\n\n"); } // Set message contents email.setMsg(result.toString()); // Set message receiver email.addTo(user.getEmail()); // Send message email.send(); logger.info("Email was sent to \"{}\".", user.getEmail()); } catch (Exception e) { logger.error("Failed to send email to \"{}\".", user.getEmail()); logger.error(e.getMessage(), e); } }
From source file:br.com.verificanf.bo.NotaBO.java
public void buscar() { /*Inicio - Pegar Configuraes de email do arquivo*/ try {//from w ww . j av a2 s. c o m String local = new File("./email.txt").getCanonicalFile().toString(); File arq = new File(local); boolean existe = arq.exists(); if (existe) { FileReader fr = new FileReader(arq); BufferedReader br = new BufferedReader(fr); while (br.ready()) { String linha = br.readLine(); if (linha.contains("host:")) { hostEmail = linha.replace("host:", "").replace(" ", ""); } if (linha.contains("port:")) { portEmail = linha.replace("port:", "").replace(" ", ""); } if (linha.contains("user:")) { userEmail = linha.replace("user:", "").replace(" ", ""); } if (linha.contains("pass:")) { passEmail = linha.replace("pass:", "").replace(" ", ""); } if (linha.contains("from:")) { fromEmail = linha.replace("from:", "").replace(" ", ""); } if (linha.contains("to:")) { toEmail = linha.replace("to:", "").replace(" ", ""); } } } } catch (FileNotFoundException ex) { Logger.getLogger(NotaBO.class.getName()).log(Level.SEVERE, null, ex); StackTraceElement st[] = ex.getStackTrace(); String erro = ""; for (int i = 0; i < st.length; i++) { erro += st[i].toString() + "\n"; } } catch (IOException ex) { Logger.getLogger(NotaBO.class.getName()).log(Level.SEVERE, null, ex); StackTraceElement st[] = ex.getStackTrace(); String erro2 = ""; for (int i = 0; i < st.length; i++) { erro2 += st[i].toString() + "\n"; } } /*FIM - Pegar Configuraes de email do arquivo*/ NotaDAO notaDAO = new NotaDAO(); try { ultimasAtual = notaDAO.getUltimaNotaMesAtual(); ultimasAnterior = notaDAO.getUltimaNotaMesAnterior(); naoEncontradas = new ArrayList<>(); for (Nota notaAnterior : ultimasAnterior) { for (Nota notaAtual : ultimasAtual) { if (notaAnterior.getLoja() == notaAtual.getLoja()) { //System.out.println("Anterior Loja: "+notaAnterior.getLoja()+" Nota: "+notaAnterior.getNumero()); //System.out.println("Atual Loja: "+notaAtual.getLoja()+" Nota: "+notaAtual.getNumero()); Integer numero = 0; for (Integer i = notaAnterior.getNumero(); i <= notaAtual.getNumero(); i++) { numero = i; Nota notacorrente = new Nota(); notacorrente.setLoja(notaAnterior.getLoja()); notacorrente.setNumero(numero); notacorrente.setSerie(notaAnterior.getSerie()); //System.out.println("Corrente Loja: "+notacorrente.getLoja()+" Nota: "+notacorrente.getNumero()); if (!notaDAO.notaIsValida(notacorrente)) { System.out.println("Loja " + notaAnterior.getLoja() + " Numero: " + numero); naoEncontradas.add(notacorrente); msg = msg.concat(" Loja: " + notacorrente.getLoja() + " Nota: " + notacorrente.getNumero() + " Serie: " + notacorrente.getSerie() + " \n"); } } } } } if (naoEncontradas.size() > 0) { Email email = new SimpleEmail(); email.setHostName(hostEmail); email.setSmtpPort(Integer.parseInt(portEmail)); email.setAuthentication(userEmail, passEmail); email.setFrom(fromEmail); email.setSubject("Alerta Nerus!!"); email.setMsg(msg); email.addTo(toEmail); email.send(); } } catch (Exception ex) { Logger.getLogger(NotaBO.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.neu.controller.MessageController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource"); String action = request.getParameter("action"); ModelAndView mv = new ModelAndView(); HttpSession session = request.getSession(); String userName = (String) session.getAttribute("userName"); if (action.equalsIgnoreCase("reply")) { try {/*from w w w. java2s .c om*/ String receiver = request.getParameter("to"); System.out.println("Printing receiver in reply case: " + receiver); QueryRunner run = new QueryRunner(ds); ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class); UsersBean ub = run.query("select * from userstable where userName =?", user, receiver); if (ub != null) { System.out.println("printing userEmail received from DB: " + ub.getUserEmail()); mv.addObject("toEmail", ub.getUserEmail()); mv.addObject("to", receiver); } mv.setViewName("reply"); } catch (SQLException e) { System.out.println(e); } } else if (action.equalsIgnoreCase("sent")) { System.out.println("In sent case"); try { String receiver = request.getParameter("to"); String receiverEmail = request.getParameter("toEmail"); System.out.println("printing receiver email: " + receiverEmail); QueryRunner run = new QueryRunner(ds); ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class); UsersBean ub = run.query("select * from userstable where userName =?", user, userName); if (ub != null) { String senderEmail = ub.getUserEmail(); System.out.println("printing senderemail: " + senderEmail); ResultSetHandler<MessageBean> msg = new BeanHandler<MessageBean>(MessageBean.class); Object[] params = new Object[4]; params[0] = userName; params[1] = request.getParameter("message"); Date d = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd"); String messageDate = format.format(d); params[2] = messageDate; params[3] = receiver; int inserts = run.update( "Insert into messages (fromUser,message,messageDate,userName) values(?,?,?,?)", params);//Logic to send the email try { Email email = new SimpleEmail(); email.setHostName("smtp.googlemail.com");//If a server is capable of sending email, then you don't need the authentication. In this case, an email server needs to be running on that machine. Since we are running this application on the localhost and we don't have a email server, we are simply asking gmail to relay this email. email.setSmtpPort(465); email.setAuthenticator( new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc")); email.setSSLOnConnect(true); email.setFrom(senderEmail);//This email will appear in the from field of the sending email. It doesn't have to be a real email address.This could be used for phishing/spoofing! email.setSubject("Thanks for Signing Up!"); email.setMsg("Welcome to Web tools Lab 5 Spring Application sign up email test!"); email.addTo(receiverEmail);//Will come from the database email.send(); } catch (Exception e) { System.out.println("Email Exception" + e.getMessage()); e.printStackTrace(); } mv.setViewName("messageSent"); } else { mv.addObject("error", "true"); mv.setViewName("index"); } } catch (Exception ex) { System.out.println("Error Message" + ex.getMessage()); ex.printStackTrace(); } } return mv; }
From source file:edu.corgi.uco.sendEmails.java
public void sendConfirmation(String email2, String firstName, String lastName, int token, int id) throws EmailException { Email email = new SimpleEmail(); email.setDebug(true);// w ww.j av a 2s . com email.setHostName("smtp.gmail.com"); email.setAuthenticator(new DefaultAuthenticator("ucocorgi2@gmail.com", "ucodrsung")); email.setStartTLSEnabled(true); email.setSmtpPort(587); email.setFrom("ucocorgi@gmail.com", "UCO CS Corgi"); email.setSubject("Account Confirmation"); email.setMsg(firstName + " " + lastName + " please go to the following address http://localhost:8080/Corgi/faces/accountAuth.xhtml " + "and enter the token:" + token + " and the ID:" + id + " to confirm and activate your account"); System.out.print("Email Address: " + email2); email.addTo(email2); email.send(); }
From source file:com.swissbit.ifttt.IFTTTConfgurationImpl.java
/** {@inheritDoc} */ @Override/* ww w . jav a 2 s .c o m*/ public void trigger() { LOGGER.debug("IFTTT Email is getting sent..."); final List<String> tags = this.retrieveHashtags(this.m_hashTags); if (tags.size() == 0) { return; } if (tags.size() > 0) { for (final String tag : tags) { try { final Email email = new SimpleEmail(); email.setHostName(this.m_smtpHost); email.setSmtpPort(this.m_smtpPort); email.setAuthenticator(new DefaultAuthenticator(this.m_smtpUsername, this.m_smtpPassword)); email.setSSL(true); email.setFrom(this.m_smtpUsername); email.setSubject(tag); email.setMsg("This is a test mail ... :-)"); email.addTo(TRIGGER_EMAIL); email.send(); } catch (final EmailException e) { LOGGER.error(Throwables.getStackTraceAsString(e)); } } } LOGGER.debug("IFTTT Email is sent...Done"); }
From source file:com.neu.controller.LoginController.java
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { DataSource ds = (DataSource) this.getApplicationContext().getBean("myDataSource"); String action = request.getParameter("action"); ModelAndView mv = new ModelAndView(); HttpSession session = request.getSession(); if (action.equalsIgnoreCase("login")) { try {/* w ww . j a va 2s .c o m*/ String userName = request.getParameter("user"); String password = request.getParameter("password"); QueryRunner run = new QueryRunner(ds); ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class); Object[] params = new Object[2]; params[0] = userName; params[1] = password; UsersBean ub = run.query("select * from userstable where userName =? and userPassword=?", user, params); if (ub != null) { ResultSetHandler<List<MessageBean>> messages = new BeanListHandler<MessageBean>( MessageBean.class); List<MessageBean> msg = run.query("select * from messages where userName =?", messages, userName); session.setAttribute("userName", userName); session.setAttribute("messageList", msg); mv.setViewName("userhome"); } else { mv.addObject("error", "true"); mv.setViewName("index"); } } catch (Exception ex) { System.out.println("Error Message" + ex.getMessage()); } } else if (action.equalsIgnoreCase("logout")) { session.invalidate(); mv.setViewName("index"); } else if (action.equalsIgnoreCase("signup")) { System.out.println("sign up"); // // String userName = request.getParameter("user"); // String password = request.getParameter("password"); // String emailObj = request.getParameter("emailObj"); // // System.out.println("printing details: " + userName + " " +password + " "+emailObj); mv.setViewName("signup"); } else if (action.equalsIgnoreCase("signupsubmit")) { System.out.println("sign up submit"); String userName = request.getParameter("user"); String password = request.getParameter("password"); String email = request.getParameter("email"); System.out.println("printing details: " + userName + " " + password + " " + email); if (userName.equals("") || (password.equals("")) || (email.equals(""))) { System.out.println("empty values"); mv.addObject("error", "true"); } else { ResultSetHandler<UsersBean> user = new BeanHandler<UsersBean>(UsersBean.class); Object[] params = new Object[3]; params[0] = userName; params[1] = password; params[2] = email; QueryRunner run = new QueryRunner(ds); int inserts = run.update("insert into userstable (UserName,UserPassword,UserEmail) values (?,?,?)", params);//Logic to insert into table System.out.println("inserts value " + inserts); if (inserts > 0) { mv.addObject("success", "true"); Email emailObj = new SimpleEmail(); emailObj.setHostName("smtp.googlemail.com");//If a server is capable of sending emailObj, then you don't need the authentication. In this case, an emailObj server needs to be running on that machine. Since we are running this application on the localhost and we don't have a emailObj server, we are simply asking gmail to relay this emailObj. emailObj.setSmtpPort(465); emailObj.setAuthenticator( new DefaultAuthenticator("contactapplication2017@gmail.com", "springmvc")); emailObj.setSSLOnConnect(true); emailObj.setFrom("webtools@hello.com");//This emailObj will appear in the from field of the sending emailObj. It doesn't have to be a real emailObj address.This could be used for phishing/spoofing! emailObj.setSubject("TestMail"); emailObj.setMsg("This is spring MVC Contact Application sending you the email"); emailObj.addTo(email);//Will come from the sign up details emailObj.send(); } } mv.setViewName("signup"); } return mv; }
From source file:com.intuit.wasabi.email.impl.EmailServiceImpl.java
void send(String subject, String msg, String... to) { String[] clearTo = removeInvalidEmails(to); if (isActive()) { try {/*from w ww . java 2 s . c o m*/ Email email = createSimpleMailService(); email.setHostName(host); email.setFrom(from); email.setSubject(subjectPrefix + " " + subject); email.setMsg(msg); email.addTo(clearTo); email.send(); } catch (EmailException mailExcp) { LOGGER.error("Email could not be send because of " + mailExcp.getMessage()); throw new WasabiEmailException("Email: " + emailToString(subject, msg, to) + " could not be sent.", mailExcp); } } else { //if the service is not active log the email that would have been send and throw error LOGGER.info("EmailService would have sent: " + emailToString(subject, msg, to)); throw new WasabiEmailException(ErrorCode.EMAIL_NOT_ACTIVE_ERROR, "The EmailService is not active."); } }
From source file:fr.gael.dhus.messaging.mail.MailServer.java
public void send(Email email, String to, String cc, String bcc, String subject) throws EmailException { email.setHostName(getSmtpServer()); email.setSmtpPort(getPort());/* w w w . ja va 2 s.c om*/ if (getUsername() != null) { email.setAuthentication(getUsername(), getPassword()); } if (getFromMail() != null) { if (getFromName() != null) email.setFrom(getFromMail(), getFromName()); else email.setFrom(getFromMail()); } if (getReplyto() != null) { try { email.setReplyTo(ImmutableList.of(new InternetAddress(getReplyto()))); } catch (AddressException e) { logger.error("Cannot configure Reply-to (" + getReplyto() + ") into the mail: " + e.getMessage()); } } // Message configuration email.setSubject("[" + cfgManager.getNameConfiguration().getShortName() + "] " + subject); email.addTo(to); // Add CCed if (cc != null) { email.addCc(cc); } // Add BCCed if (bcc != null) { email.addBcc(bcc); } email.setStartTLSEnabled(isTls()); try { email.send(); } catch (EmailException e) { logger.error("Cannot send email: " + e.getMessage()); throw e; } }