List of usage examples for javax.mail.internet InternetAddress InternetAddress
public InternetAddress(String address) throws AddressException
From source file:eagle.common.email.EagleMailClient.java
private boolean _send(String from, String to, String cc, String title, String content) { Message msg = new MimeMessage(session); try {/*www .j a v a 2s . co m*/ msg.setFrom(new InternetAddress(from)); msg.setSubject(title); if (to != null) { msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); } if (cc != null) { msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc)); } //msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(DEFAULT_BCC_ADDRESS)); msg.setContent(content, "text/html;charset=utf-8"); LOG.info(String.format("Going to send mail: from[%s], to[%s], cc[%s], title[%s]", from, to, cc, title)); Transport.send(msg); return true; } catch (AddressException e) { LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e); return false; } catch (MessagingException e) { LOG.info("Send mail failed, got an AddressException: " + e.getMessage(), e); return false; } }
From source file:org.topazproject.ambra.email.impl.FreemarkerTemplateMailer.java
/** * Mail the email formatted using the given templates * @param toEmailAddresses List of email addresses to which emails should be sent. White space delimited. * @param fromEmailAddress fromEmailAddress * @param subject subject of the email//from w w w .jav a2s. c o m * @param context context to set the values from for the template * @param textTemplateFilename textTemplateFilename * @param htmlTemplateFilename htmlTemplateFilename */ public void mail(final String toEmailAddresses, final String fromEmailAddress, final String subject, final Map<String, Object> context, final String textTemplateFilename, final String htmlTemplateFilename) { final StringTokenizer emailTokens = new StringTokenizer(toEmailAddresses); while (emailTokens.hasMoreTokens()) { final String toEmailAddress = emailTokens.nextToken(); final MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(final MimeMessage mimeMessage) throws MessagingException, IOException { final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, configuration.getDefaultEncoding()); message.setTo(new InternetAddress(toEmailAddress)); message.setFrom(new InternetAddress(fromEmailAddress, (String) context.get(USER_NAME_KEY))); message.setSubject(subject); // Create a "text" Multipart message final Multipart mp = createPartForMultipart(textTemplateFilename, context, "alternative", MIME_TYPE_TEXT_PLAIN + "; charset=" + configuration.getDefaultEncoding()); // Create a "HTML" Multipart message final Multipart htmlContent = createPartForMultipart(htmlTemplateFilename, context, "related", MIME_TYPE_TEXT_HTML + "; charset=" + configuration.getDefaultEncoding()); final BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(htmlContent); mp.addBodyPart(htmlPart); mimeMessage.setContent(mp); } }; mailSender.send(preparator); if (log.isDebugEnabled()) { log.debug("Mail sent to:" + toEmailAddress); } } }
From source file:com.linuxbox.enkive.statistics.StatsReportEmailer.java
public void sendReport() { // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", mailHost); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try { // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); // Set To: header field of the header. for (String toAddress : to.split(";")) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); }// w w w . jav a2 s. c o m // Set Subject: header field message.setSubject("Enkive Status Report"); // Now set the actual message message.setText(buildReport()); // Send message Transport.send(message); } catch (MessagingException mex) { LOGGER.warn("Error sending statistics report email", mex); } }
From source file:mail.MailService.java
/** * Erstellt eine kanonisierte MIME-Mail. * @param email/*from ww w. j a va 2 s.c o m*/ * @throws MessagingException * @throws IOException */ public String createMail2(Mail email, Config config) throws MessagingException, IOException { byte[] mailAsBytes = email.getText(); int laenge = mailAsBytes.length + getCRLF().length; byte[] bOout = new byte[laenge]; for (int i = 0; i < mailAsBytes.length; i++) { bOout[i] = mailAsBytes[i]; } byte[] neu = getCRLF(); int counter = 0; for (int i = mailAsBytes.length; i < laenge; i++) { bOout[i] = neu[counter]; counter++; } email.setText(bOout); Properties props = new Properties(); props.put("mail.smtp.host", "mail.java-tutor.com"); Session session = Session.getDefaultInstance(props); Message 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(email.getText())); msg.saveChanges(); /* // Erstellen des Content MimeMultipart content = new MimeMultipart("text"); MimeBodyPart part = new MimeBodyPart(); part.setText(email.getText()); part.setHeader("MIME-Version" , "1.0"); part.setHeader("Content-Type" , part.getContentType()); content.addBodyPart(part); System.out.println(content.getContentType()); Message msg = new MimeMessage(session); msg.setContent(content); msg.setHeader("MIME-Version" , "1.0"); msg.setHeader("Content-Type" , content.getContentType()); InternetAddress addressFrom = new InternetAddress(email.getAbsender()); msg.setFrom(addressFrom); InternetAddress addressTo = new InternetAddress(email.getEmpfnger()); msg.setRecipient(Message.RecipientType.TO, addressTo); msg.setSubject(email.getBetreff()); msg.setSentDate(email.getAbsendeDatum()); */ //msg.setContent(email.getText(), "text/plain"); // 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 2"); 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(Charset.defaultCharset().name())); }
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;//from www . java 2s . c o m try { 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(); } } }
From source file:hudson.maven.reporters.MavenMailerTest.java
/** * Test using the list of recipients of TAG ciManagement defined in * ModuleRoot for all the modules./* www. j a va 2 s . c om*/ * * @throws Exception */ @Test @Bug(1201) public void testCiManagementNotificationRoot() throws Exception { JenkinsLocationConfiguration.get().setAdminAddress(EMAIL_ADMIN); Mailbox yourInbox = Mailbox.get(new InternetAddress(EMAIL_SOME)); Mailbox jenkinsConfiguredInbox = Mailbox.get(new InternetAddress(EMAIL_JENKINS_CONFIGURED)); yourInbox.clear(); jenkinsConfiguredInbox.clear(); j.configureDefaultMaven(); MavenModuleSet mms = j.createMavenProject(); mms.setGoals("test"); mms.setScm(new ExtractResourceSCM(getClass().getResource("/hudson/maven/JENKINS-1201-parent-defined.zip"))); MavenMailer m = new MavenMailer(); m.recipients = EMAIL_JENKINS_CONFIGURED; m.perModuleEmail = true; mms.getReporters().add(m); j.assertBuildStatus(Result.UNSTABLE, mms.scheduleBuild2(0).get()); assertEquals(2, yourInbox.size()); assertEquals(2, jenkinsConfiguredInbox.size()); Message message = yourInbox.get(0); assertEquals(2, message.getAllRecipients().length); assertContainsRecipient(EMAIL_SOME, message); assertContainsRecipient(EMAIL_JENKINS_CONFIGURED, message); message = yourInbox.get(1); assertEquals(2, message.getAllRecipients().length); assertContainsRecipient(EMAIL_SOME, message); assertContainsRecipient(EMAIL_JENKINS_CONFIGURED, message); message = jenkinsConfiguredInbox.get(0); assertEquals(2, message.getAllRecipients().length); assertContainsRecipient(EMAIL_SOME, message); assertContainsRecipient(EMAIL_JENKINS_CONFIGURED, message); message = jenkinsConfiguredInbox.get(1); assertEquals(2, message.getAllRecipients().length); assertContainsRecipient(EMAIL_SOME, message); assertContainsRecipient(EMAIL_JENKINS_CONFIGURED, message); }
From source file:com.norconex.jef4.mail.SimpleMailer.java
/** * Sends an email.//from w ww .j av a 2 s . com * @param recipients email recipients ("To" field) * @param subject email subject * @param body email body (content) * @throws MessagingException problem sending email */ public final void send(final String[] recipients, final String subject, final String body) throws MessagingException { if (recipients == null || recipients.length == 0) { throw new IllegalArgumentException("No mail recipient provided."); } Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(sender)); for (int i = 0; i < recipients.length; i++) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients[i])); } message.setSubject(subject); message.setContent(body, contentType); Transport.send(message); }
From source file:eu.planets_project.pp.plato.action.session.ExceptionAction.java
@RaiseEvent("exceptionHandled") public String sendMail() { try {// w w w .j a va 2s . co m log.debug(body); Properties props = System.getProperties(); Properties mailProps = new Properties(); mailProps.load(ExceptionAction.class.getResourceAsStream("/mail.properties")); props.put("mail.smtp.host", mailProps.getProperty("SMTPSERVER")); Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(mailProps.getProperty("FROM"))); message.setRecipient(RecipientType.TO, new InternetAddress(mailProps.getProperty("TO"))); String exceptionType = "Unknown"; String exceptionMessage = ""; String stackTrace = ""; String host = ((HttpServletRequest) facesContext.getExternalContext().getRequest()).getLocalName(); if (lastHandledException != null) { exceptionType = lastHandledException.getClass().getCanonicalName(); exceptionMessage = lastHandledException.getMessage(); StringWriter writer = new StringWriter(); lastHandledException.printStackTrace(new PrintWriter(writer)); stackTrace = writer.toString(); } message.setSubject("[PlatoError] " + exceptionType + " at " + host); StringBuilder builder = new StringBuilder(); builder.append("Date: " + format.format(new Date()) + "\n"); builder.append("User: " + ((user == null) ? "Unknown" : user.getUsername()) + "\n"); builder.append("ExceptionType: " + exceptionType + "\n"); builder.append("ExceptionMessage: " + exceptionMessage + "\n\n"); builder.append("UserMail:" + separatorLine + this.userEmail + separatorLine + "\n"); builder.append("User Description:" + separatorLine + this.body + separatorLine + "\n"); builder.append(stackTrace); message.setText(builder.toString()); message.saveChanges(); Transport.send(message); this.lastHandledException = null; facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Bugreport sent.", "Thank you for your feedback. We will try to analyse and resolve the issue as soon as possible.")); } catch (Exception e) { log.debug(e.getMessage(), e); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Bugreport couldn't be sent", "Because of an enternal error your bug report couldn't be sent. We apologise for this and hope you are willing to inform us about this so we can fix the problem. " + "Please send an email to plato@ifs.tuwien.ac.at with a " + "description of what you have been doing at the time of the error." + "Thank you very much!")); return null; } return "home"; }
From source file:com.formkiq.core.service.notification.ExternalMailSender.java
/** * Send Reset Email.//from w w w . j a v a 2 s .co m * @param to {@link String} * @param email {@link String} * @param subject {@link String} * @param text {@link String} * @param html {@link String} * @throws MessagingException MessagingException */ private void sendResetEmail(final String to, final String email, final String subject, final String text, final String html) throws MessagingException { String hostname = this.systemProperties.getSystemHostname(); String resetToken = this.userservice.generateResetToken(to); StringSubstitutor s = new StringSubstitutor( ImmutableMap.of("hostname", hostname, "to", to, "email", email, "resettoken", resetToken)); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(s.replace(text), "UTF-8"); s.replace(html); MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(s.replace(html), "text/html;charset=UTF-8"); final Multipart mp = new MimeMultipart("alternative"); mp.addBodyPart(textPart); mp.addBodyPart(htmlPart); MimeMessage msg = this.mail.createMimeMessage(); msg.setContent(mp); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setSubject(subject); this.mail.send(msg); }
From source file:com.nokia.helium.core.EmailDataSender.java
/** * Get recipient address list.//from www . jav a2 s . c o m * * @return Recipient address list. */ private InternetAddress[] getToAddressList() { int toListLength = 0; if (toAddressList != null) { toListLength = toAddressList.length; } InternetAddress[] addressList = new InternetAddress[toListLength]; try { log.debug("getToAddressList:length: " + toListLength); for (int i = 0; i < toListLength; i++) { log.debug("getToAddressList:address:" + toAddressList[i]); addressList[i] = new InternetAddress(toAddressList[i]); } } catch (AddressException aex) { log.error("AddressException: " + aex); } return addressList; }