List of usage examples for javax.mail.internet InternetAddress InternetAddress
public InternetAddress(String address) throws AddressException
From source file:eu.scape_project.pw.idp.UserManager.java
/** * Sends the user a link to reset the password. * /*from w w w . ja v a2 s .c o m*/ * @param user * the user * @param serverString * host and port of the server * @throws CannotSendMailException * if the password reset mail could not be sent */ public void sendPasswordResetMail(IdpUser user, String serverString) throws CannotSendMailException { try { Properties props = System.getProperties(); props.put("mail.smtp.host", config.getString("mail.smtp.host")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(config.getString("mail.from"))); message.setRecipient(RecipientType.TO, new InternetAddress(user.getEmail())); message.setSubject("Planningsuite password recovery"); StringBuilder builder = new StringBuilder(); builder.append("Dear " + user.getFirstName() + " " + user.getLastName() + ", \n\n"); builder.append("You have requested help recovering the password for the Plato user "); builder.append(user.getUsername()).append(".\n\n"); builder.append("Please use the following link to reset your Planningsuite password: \n"); builder.append("http://" + serverString + "/idp/resetPassword.jsf?uid=" + user.getActionToken()); builder.append("\n\n--\n"); builder.append("Your Planningsuite team"); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); log.debug("Sent password reset mail to " + user.getEmail()); } catch (Exception e) { log.error("Error at sending password reset mail to {}", user.getEmail()); throw new CannotSendMailException("Error at sending password reset mail to " + user.getEmail()); } }
From source file:com.redhat.rhn.manager.user.CreateUserCommand.java
/** * Private helper method to validate the user's email address. Puts errors into the * errors list./*from w w w . j a v a 2 s. c o m*/ */ private void validateEmail() { // Make sure user and email are not null if (user == null || user.getEmail() == null) { errors.add(new ValidatorError("error.addr_invalid", "null")); return; } // Make email is not over the max length if (user.getEmail().length() > UserDefaults.get().getMaxEmailLength()) { errors.add(new ValidatorError("error.maxemail")); return; } // Make sure set email is valid try { new InternetAddress(user.getEmail()).validate(); } catch (AddressException e) { errors.add(new ValidatorError("error.addr_invalid", user.getEmail())); } }
From source file:nc.noumea.mairie.appock.core.utility.AppockUtil.java
public static boolean isValidEmailAddress(String email) { if (StringUtils.isBlank(email)) { return false; }/* w w w.ja v a 2 s .c o m*/ boolean result = true; try { InternetAddress emailAddr = new InternetAddress(email); emailAddr.validate(); } catch (AddressException ex) { result = false; } return result; }
From source file:com.email.SendEmailCalInvite.java
/** * Builds the calendar invite for the email * * @param eml EmailOutInvitesModel//from w w w. j a v a 2 s . c o m * @return BodyPart (calendar invite) */ private static BodyPart responseDueCalObject(EmailOutInvitesModel eml, SystemEmailModel account) { BodyPart calendarPart = new MimeBodyPart(); try { String calendarContent = "BEGIN:VCALENDAR\n" + "METHOD:REQUEST\n" + "PRODID: BCP - Meeting\n" + "VERSION:2.0\n" + "BEGIN:VEVENT\n" + "DTSTAMP:" + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + "\n" + "DTSTART:" + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + "\n" + "DTEND:" + Global.getiCalendarDateFormat().format(eml.getHearingEndTime()) + "\n" //Subject + "SUMMARY: " + "ResponseDue" + "\n" + "UID:" + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + Global.getiCalendarDateFormat().format(eml.getHearingEndTime()) + "\n" //return email + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:" + new InternetAddress(account.getEmailAddress()).getAddress() + "\n" //return email + "ORGANIZER:MAILTO:" + new InternetAddress(account.getEmailAddress()).getAddress() + "\n" //hearing room + "LOCATION: " + "\n" //subject + "DESCRIPTION: " + "\n" + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n" + "STATUS:CONFIRMED\n" + "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:REMINDER\n" + "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR"; calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage"); calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL"); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } return calendarPart; }
From source file:Implement.DAO.CommonDAOImpl.java
@Override public boolean sendMail(String title, String receiver, String messageContent) throws MessagingException { final String username = "registration@youtripper.com"; final String password = "Tripregister190515"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "mail.youtripper.com"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); }/*from w ww . ja v a2 s . c o m*/ }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress("registration@youtripper.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver)); message.setSubject(title); message.setContent(messageContent, "text/html; charset=utf-8"); Transport.send(message); return true; }
From source file:com.mgmtp.perfload.perfalyzer.reporting.email.EmailReporter.java
private void sendMessage(final String subject, final String content) { try {/*w ww .j a v a 2 s . c o m*/ Session session = (authenticator != null) ? Session.getInstance(smtpProps, authenticator) : Session.getInstance(smtpProps); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(fromAddress)); msg.setSubject(subject); msg.addRecipients(Message.RecipientType.TO, on(',').join(toAddresses)); msg.setText(content, UTF_8.name(), "html"); Transport.send(msg); } catch (MessagingException e) { log.error("Error while creating report e-mail", e); } }
From source file:com.evolveum.midpoint.notifications.impl.api.transports.MailTransport.java
@Override public void send(Message mailMessage, String transportName, Task task, OperationResult parentResult) { OperationResult result = parentResult.createSubresult(DOT_CLASS + "send"); result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo()); result.addParam("mailMessage subject", mailMessage.getSubject()); SystemConfigurationType systemConfiguration = NotificationsUtil .getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy")); if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null || systemConfiguration.getNotificationConfiguration().getMail() == null) { String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo() + " will not be sent."; LOGGER.warn(msg);//from w ww . j av a 2 s.c om result.recordWarning(msg); return; } MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail(); String redirectToFile = mailConfigurationType.getRedirectToFile(); if (redirectToFile != null) { try { TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage)); result.recordSuccess(); } catch (IOException e) { LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile); result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e); } return; } if (mailConfigurationType.getServer().isEmpty()) { String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo() + " will not be sent."; LOGGER.warn(msg); result.recordWarning(msg); return; } long start = System.currentTimeMillis(); String from = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom() : "nobody@nowhere.org"; for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) { OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer"); final String host = mailServerConfigurationType.getHost(); resultForServer.addContext("server", host); resultForServer.addContext("port", mailServerConfigurationType.getPort()); Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); if (mailServerConfigurationType.getPort() != null) { properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort())); } MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType .getTransportSecurity(); boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false; switch (mailTransportSecurityType) { case STARTTLS_ENABLED: starttlsEnable = true; break; case STARTTLS_REQUIRED: starttlsEnable = true; starttlsRequired = true; break; case SSL: sslEnabled = true; break; } properties.put("mail.smtp.ssl.enable", "" + sslEnabled); properties.put("mail.smtp.starttls.enable", "" + starttlsEnable); properties.put("mail.smtp.starttls.required", "" + starttlsRequired); if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) { properties.put("mail.debug", "true"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Using mail properties: "); for (Object key : properties.keySet()) { if (key instanceof String && ((String) key).startsWith("mail.")) { LOGGER.debug(" - " + key + " = " + properties.get(key)); } } } task.recordState("Sending notification mail via " + host); Session session = Session.getInstance(properties); try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(from)); for (String recipient : mailMessage.getTo()) { mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); } mimeMessage.setSubject(mailMessage.getSubject(), "utf-8"); String contentType = mailMessage.getContentType(); if (StringUtils.isEmpty(contentType)) { contentType = "text/plain; charset=UTF-8"; } mimeMessage.setContent(mailMessage.getBody(), contentType); javax.mail.Transport t = session.getTransport("smtp"); if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) { ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword(); String password = null; if (passwordProtected != null) { try { password = protector.decryptString(passwordProtected); } catch (EncryptionException e) { String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any."; LoggingUtils.logException(LOGGER, msg, e); resultForServer.recordFatalError(msg, e); continue; } } t.connect(mailServerConfigurationType.getUsername(), password); } else { t.connect(); } t.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + "."); resultForServer.recordSuccess(); result.recordSuccess(); long duration = System.currentTimeMillis() - start; task.recordState( "Notification mail sent successfully via " + host + ", in " + duration + " ms overall."); task.recordNotificationOperation(NAME, true, duration); return; } catch (MessagingException e) { String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host + ", trying another mail server, if there is any"; LoggingUtils.logException(LOGGER, msg, e); resultForServer.recordFatalError(msg, e); task.recordState("Error sending notification mail via " + host); } } LOGGER.warn( "No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent."); result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent."); task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start); }
From source file:Mailer.java
/** Send the message. *///www . j av a 2s . c om public synchronized void doSend() throws MessagingException { if (!isComplete()) throw new IllegalArgumentException("doSend called before message was complete"); /** Properties object used to pass props into the MAIL API */ Properties props = new Properties(); props.put("mail.smtp.host", mailHost); // Create the Session object if (session == null) { session = Session.getDefaultInstance(props, null); if (verbose) session.setDebug(true); // Verbose! } // create a message final Message mesg = new MimeMessage(session); InternetAddress[] addresses; // TO Address list addresses = new InternetAddress[toList.size()]; for (int i = 0; i < addresses.length; i++) addresses[i] = new InternetAddress((String) toList.get(i)); mesg.setRecipients(Message.RecipientType.TO, addresses); // From Address mesg.setFrom(new InternetAddress(from)); // CC Address list addresses = new InternetAddress[ccList.size()]; for (int i = 0; i < addresses.length; i++) addresses[i] = new InternetAddress((String) ccList.get(i)); mesg.setRecipients(Message.RecipientType.CC, addresses); // BCC Address list addresses = new InternetAddress[bccList.size()]; for (int i = 0; i < addresses.length; i++) addresses[i] = new InternetAddress((String) bccList.get(i)); mesg.setRecipients(Message.RecipientType.BCC, addresses); // The Subject mesg.setSubject(subject); // Now the message body. mesg.setText(body); // Finally, send the message! (use static Transport method) // Do this in a Thread as it sometimes is too slow for JServ // new Thread() { // public void run() { // try { Transport.send(mesg); // } catch (MessagingException e) { // throw new IllegalArgumentException( // "Transport.send() threw: " + e.toString()); // } // } // }.start(); }
From source file:mitm.application.djigzo.james.mailets.MailAddressHandlerTest.java
@Test public void mailAddressHandler() throws Exception { final MutableInt count = new MutableInt(); MailAddressHandler.HandleUserEventHandler eventHandler = new MailAddressHandler.HandleUserEventHandler() { @Override/*from w w w. j av a 2 s.com*/ public void handleUser(User user) throws MessagingException { count.increment(); throw new ConstraintViolationException("Dummy ConstraintViolationException", null, ""); } }; MailAddressHandler handler = new MailAddressHandler(sessionManager, userWorkflow, actionExecutor, eventHandler, 0); Collection<MailAddress> recipients = MailAddressUtils .fromAddressArrayToMailAddressList(new InternetAddress("test@example.com")); try { handler.handleMailAddresses(recipients); fail(); } catch (MessagingException e) { assertTrue(ExceptionUtils.getRootCause(e) instanceof ConstraintViolationException); } assertEquals(1, count.intValue()); }
From source file:mail.MailService.java
/** * Erstellt eine MIME-Mail inkl. Transfercodierung. * @param email//from w w w . j ava 2s.c o m * @throws MessagingException * @throws IOException */ public String createMail3(Mail email, Config config) throws MessagingException, IOException { byte[] mailAsBytes = email.getText(); byte[] outputBytes; // Transfercodierung anwenden if (config.getTranscodeDescription().equals(Config.BASE64)) { outputBytes = encodeBase64(mailAsBytes); } else if (config.getTranscodeDescription().equals(Config.QP)) { outputBytes = encodeQuotedPrintable(mailAsBytes); } else { outputBytes = mailAsBytes; } email.setText(outputBytes); Properties props = new Properties(); props.put("mail.smtp.host", "mail.java-tutor.com"); Session session = Session.getDefaultInstance(props); MimeMessage msg = new MimeMessage(session); // msg.setHeader("MIME-Version" , "1.0"); // msg.setHeader("Content-Type" , "text/plain"); // Absender InternetAddress addressFrom = new InternetAddress(email.getAbsender()); msg.setFrom(addressFrom); // Empfnger InternetAddress addressTo = new InternetAddress(email.getEmpfaenger()); msg.setRecipient(Message.RecipientType.TO, addressTo); msg.setSubject(email.getBetreff()); msg.setSentDate(email.getAbsendeDatum()); msg.setText(Utils.toString(outputBytes)); msg.saveChanges(); // Mail in Ausgabestrom schreiben ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { msg.writeTo(bOut); } catch (IOException e) { System.out.println("Fehler beim Schreiben der Mail in Schritt 3"); throw e; } // String out = bOut.toString(); // int pos1 = out.indexOf("Message-ID"); // int pos2 = out.indexOf("@localhost") + 13; // String output = out.subSequence(0, pos1).toString(); // output += (out.substring(pos2)); return removeMessageId(bOut.toString().replaceAll(ITexte.CONTENT, "Content-Transfer-Encoding: " + config.getTranscodeDescription())); }