List of usage examples for javax.mail.internet MimeMessage MimeMessage
public MimeMessage(MimeMessage source) throws MessagingException
source
MimeMessage. 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; }// www. j a va 2 s . c o m 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:mail.MailService.java
/** * Erstellt eine kanonisierte MIME-Mail. * @param email//w w w . j av a2s . 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:transport.java
public void go(Session session, InternetAddress[] toAddr, InternetAddress from) { Transport trans = null;/*from ww w . ja v a 2 s . co m*/ try { // create a message Message msg = new MimeMessage(session); msg.setFrom(from); msg.setRecipients(Message.RecipientType.TO, toAddr); msg.setSubject("JavaMail APIs transport.java Test"); msg.setSentDate(new Date()); // Date: header msg.setContent(msgText + msgText2, "text/plain"); msg.saveChanges(); // get the smtp transport for the address trans = session.getTransport(toAddr[0]); // register ourselves as listener for ConnectionEvents // and TransportEvents trans.addConnectionListener(this); trans.addTransportListener(this); // connect the transport trans.connect(); // send the message trans.sendMessage(msg, toAddr); // give the EventQueue enough time to fire its events try { Thread.sleep(5); } catch (InterruptedException e) { } } catch (MessagingException mex) { // give the EventQueue enough time to fire its events try { Thread.sleep(5); } catch (InterruptedException e) { } System.out.println("Sending failed with exception:"); mex.printStackTrace(); System.out.println(); Exception ex = mex; do { if (ex instanceof SendFailedException) { SendFailedException sfex = (SendFailedException) ex; Address[] invalid = sfex.getInvalidAddresses(); if (invalid != null) { System.out.println(" ** Invalid Addresses"); for (int i = 0; i < invalid.length; i++) System.out.println(" " + invalid[i]); } Address[] validUnsent = sfex.getValidUnsentAddresses(); if (validUnsent != null) { System.out.println(" ** ValidUnsent Addresses"); for (int i = 0; i < validUnsent.length; i++) System.out.println(" " + validUnsent[i]); } Address[] validSent = sfex.getValidSentAddresses(); if (validSent != null) { System.out.println(" ** ValidSent Addresses"); for (int i = 0; i < validSent.length; i++) System.out.println(" " + validSent[i]); } } System.out.println(); if (ex instanceof MessagingException) ex = ((MessagingException) ex).getNextException(); else ex = null; } while (ex != null); } finally { try { // close the transport if (trans != null) trans.close(); } catch (MessagingException mex) { /* ignore */ } } }
From source file:org.obm.imap.archive.services.MailerImpl.java
@Override public void send(ObmDomain domain, ArchiveTreatmentRunId runId, State state, Mailing mailing) throws MessagingException, URISyntaxException { try {//from w w w . j a va 2 s . c o m if (!mailing.getEmailAddresses().isEmpty()) { MimeMessage message = new MimeMessage(session); message.setFrom(from(domain)); message.addRecipients(RecipientType.TO, internetAddresses(mailing)); message.setSubject("End of IMAP Archive for domain " + domain.getName()); message.setText(text(domain, runId, state), Charsets.UTF_8.name()); smtpService.sendEmail(message, session); } } catch (MessagingException | URISyntaxException e) { logger.error("Error when mailing", e); throw e; } }
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 ww.j ava 2 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:eagle.common.email.EagleMailClient.java
private boolean _send(String from, String to, String cc, String title, String content) { Message msg = new MimeMessage(session); try {/*from w w w .ja v a 2 s. 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: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 . j ava2 s.c om*/ 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:com.emc.plants.service.impl.MailerBean.java
/** * Create a mail message and send it.//from w w w .j a v a2 s. c o m * * @param customerInfo Customer information. * @param orderKey * @throws MailerAppException */ public void createAndSendMail(CustomerInfo customerInfo, long orderKey) throws MailerAppException { try { EMailMessage eMessage = new EMailMessage(createSubjectLine(orderKey), createMessage(orderKey), customerInfo.getCustomerID()); Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: " + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents()); //Session mailSession = (Session) Util.getInitialContext().lookup(MAIL_SESSION); MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMessage.getEmailReceiver(), false)); msg.setSubject(eMessage.getSubject()); MimeBodyPart mbp = new MimeBodyPart(); mbp.setText(eMessage.getHtmlContents(), "us-ascii"); msg.setHeader("X-Mailer", "JavaMailer"); Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp); msg.setContent(mp); msg.setSentDate(new Date()); Transport.send(msg); Util.debug("\nMail sent successfully."); } catch (Exception e) { Util.debug("Error sending mail. Have mail resources been configured correctly?"); Util.debug("createAndSendMail exception : " + e); e.printStackTrace(); throw new MailerAppException("Failure while sending mail"); } }
From source file:it.infn.ct.security.actions.ReactivateUser.java
private void sendMail(LDAPUser user) throws MailException { javax.mail.Session session = null;//from ww w . j a va2 s . co m try { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); session = (javax.mail.Session) envCtx.lookup("mail/Users"); } catch (Exception ex) { _log.error("Mail resource lookup error"); _log.error(ex.getMessage()); throw new MailException("Mail Resource not available"); } Message mailMsg = new MimeMessage(session); try { mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom)); InternetAddress mailTos[] = new InternetAddress[1]; mailTos[0] = new InternetAddress(mailTo); mailMsg.setRecipients(Message.RecipientType.TO, mailTos); mailMsg.setSubject(mailSubject); mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " " + user.getSurname() + " (" + user.getUsername() + ")"); mailMsg.setText(mailBody); Transport.send(mailMsg); } catch (UnsupportedEncodingException ex) { _log.error(ex); throw new MailException("Mail address format not valid"); } catch (MessagingException ex) { _log.error(ex); throw new MailException("Mail message has problems"); } }
From source file:com.norconex.jef4.mail.SimpleMailer.java
/** * Sends an email./* ww w. ja v a 2s. c om*/ * @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); }