List of usage examples for javax.mail Message getAllRecipients
public Address[] getAllRecipients() throws MessagingException
From source file:net.fenyo.mail4hotspot.service.MailManager.java
public static void main(String[] args) throws NoSuchProviderException, MessagingException { System.out.println("Salut"); // trustSSL(); /* final Properties props = new Properties(); props.put("mail.smtp.host", "my-mail-server"); props.put("mail.from", "me@example.com"); javax.mail.Session session = javax.mail.Session.getInstance(props, null); try {//from w ww . ja v a 2s.c om MimeMessage msg = new MimeMessage(session); msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, "you@example.com"); msg.setSubject("JavaMail hello world example"); msg.setSentDate(new Date()); msg.setText("Hello, world!\n"); Transport.send(msg); } catch (MessagingException mex) { System.out.println("send failed, exception: " + mex); }*/ final Properties props = new Properties(); //props.put("mail.host", "10.69.60.6"); //props.put("mail.user", "fenyo"); //props.put("mail.from", "fenyo@fenyo.net"); //props.put("mail.transport.protocol", "smtps"); //props.put("mail.store.protocol", "pop3s"); // [javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Sun Microsystems, Inc], // javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Sun Microsystems, Inc], // javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc], // javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Sun Microsystems, Inc], // javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Sun Microsystems, Inc], // javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Sun Microsystems, Inc]] // final Provider[] providers = session.getProviders(); javax.mail.Session session = javax.mail.Session.getInstance(props, null); session.setDebug(true); //session.setDebug(false); // final Store store = session.getStore("pop3s"); // store.connect("10.69.60.6", 995, "fenyo", "PASSWORD"); // final Store store = session.getStore("imaps"); // store.connect("10.69.60.6", 993, "fenyo", "PASSWORD"); // System.out.println(store.getDefaultFolder().getMessageCount()); //final Store store = session.getStore("pop3"); final Store store = session.getStore("pop3s"); //final Store store = session.getStore("imaps"); // store.addStoreListener(new StoreListener() { // public void notification(StoreEvent e) { // String s; // if (e.getMessageType() == StoreEvent.ALERT) // s = "ALERT: "; // else // s = "NOTICE: "; // System.out.println("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX: " + s + e.getMessage()); // } // }); //store.connect("10.69.60.6", 110, "fenyo", "PASSWORD"); store.connect("pop.gmail.com", 995, "alexandre.fenyo@gmail.com", "PASSWORD"); //store.connect("localhost", 110, "alexandre.fenyo@yahoo.com", "PASSWORD"); //store.connect("localhost", 995, "fenyo@live.fr", "PASSWORD"); //store.connect("localhost", 995, "thisisatestforalex@aol.fr", "PASSWORD"); // final Folder[] folders = store.getPersonalNamespaces(); // for (Folder f : folders) { // System.out.println("Folder: " + f.getMessageCount()); // final Folder g = f.getFolder("INBOX"); // g.open(Folder.READ_ONLY); // System.out.println(" g:" + g.getMessageCount()); // } final Folder inbox = store.getDefaultFolder().getFolder("INBOX"); inbox.open(Folder.READ_ONLY); System.out.println("nmessages: " + inbox.getMessageCount()); final Message[] messages = inbox.getMessages(); for (Message message : messages) { System.out.println("message:"); System.out.println(" size: " + message.getSize()); try { if (message.getFrom() != null) System.out.println(" From: " + message.getFrom()[0]); } catch (final Exception ex) { System.out.println(ex.toString()); } System.out.println(" content-type: " + message.getContentType()); System.out.println(" disposition: " + message.getDisposition()); System.out.println(" description: " + message.getDescription()); System.out.println(" filename: " + message.getFileName()); System.out.println(" line count: " + message.getLineCount()); System.out.println(" message number: " + message.getMessageNumber()); System.out.println(" subject: " + message.getSubject()); try { if (message.getAllRecipients() != null) for (Address address : message.getAllRecipients()) System.out.println(" address: " + address); } catch (final Exception ex) { System.out.println(ex.toString()); } } for (Message message : messages) { System.out.println("-----------------------------------------------------"); Object content; try { content = message.getContent(); if (javax.mail.Multipart.class.isInstance(content)) { System.out.println("CONTENT OBJECT CLASS: MULTIPART"); final javax.mail.Multipart multipart = (javax.mail.Multipart) content; System.out.println("multipart content type: " + multipart.getContentType()); System.out.println("multipart count: " + multipart.getCount()); for (int i = 0; i < multipart.getCount(); i++) { System.out.println(" multipart body[" + i + "]: " + multipart.getBodyPart(i)); BodyPart part = multipart.getBodyPart(i); System.out.println(" content-type: " + part.getContentType()); } } else if (String.class.isInstance(content)) { System.out.println("CONTENT IS A STRING: {" + content + "}"); } else { System.out.println("CONTENT OBJECT CLASS: " + content.getClass().toString()); } } catch (IOException e) { e.printStackTrace(); } } store.close(); }
From source file:smtpsend.java
public static void main(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null;/* w ww . java 2 s .com*/ String mailer = "smtpsend"; String file = null; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; boolean verbose = false; boolean auth = false; boolean ssl = false; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-a")) { file = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-A")) { auth = true; } else if (argv[optind].equals("-S")) { ssl = true; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]"); System.out.println("\t[-v] [-A] [-S] [address]"); System.exit(1); } else { break; } } try { if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } Properties props = System.getProperties(); if (mailhost != null) props.put("mail.smtp.host", mailhost); if (auth) props.put("mail.smtp.auth", "true"); // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); // construct the message Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); String text = collect(in); if (file != null) { // Attach the specified file. // We need a multipart message to hold the attachment. MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(text); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.attachFile(file); MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); } else { // If the desired charset is known, you can use // setText(text, charset) msg.setText(text); } msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off /* * The simple way to send a message is this: * * Transport.send(msg); * * But we're going to use some SMTP-specific features for demonstration * purposes so we need to manage the Transport object explicitly. */ SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp"); try { if (auth) t.connect(mailhost, user, password); else t.connect(); t.sendMessage(msg, msg.getAllRecipients()); } finally { if (verbose) System.out.println("Response: " + t.getLastServerResponse()); t.close(); } System.out.println("\nMail was sent successfully."); // Keep a copy, if requested. if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { if (e instanceof SendFailedException) { MessagingException sfe = (MessagingException) e; if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; System.out.println("SMTP SEND FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else { if (verbose) System.out.println("Send failed: " + sfe.toString()); } Exception ne; while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) { sfe = (MessagingException) ne; if (sfe instanceof SMTPAddressFailedException) { SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe; System.out.println("ADDRESS FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else if (sfe instanceof SMTPAddressSucceededException) { System.out.println("ADDRESS SUCCEEDED:"); SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe; if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } } } else { System.out.println("Got Exception: " + e); if (verbose) e.printStackTrace(); } } }
From source file:smtpsend.java
/** * Example of how to extend the SMTPTransport class. * This example illustrates how to issue the XACT * command before the SMTPTransport issues the DATA * command./* w w w . j a va 2s . c om*/ * public static class SMTPExtension extends SMTPTransport { public SMTPExtension(Session session, URLName url) { super(session, url); // to check that we're being used System.out.println("SMTPExtension: constructed"); } protected synchronized OutputStream data() throws MessagingException { if (supportsExtension("XACCOUNTING")) issueCommand("XACT", 250); return super.data(); } } */ public static void main(String[] argv) { String to, subject = null, from = null, cc = null, bcc = null, url = null; String mailhost = null; String mailer = "smtpsend"; String file = null; String protocol = null, host = null, user = null, password = null; String record = null; // name of folder in which to record mail boolean debug = false; boolean verbose = false; boolean auth = false; String prot = "smtp"; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int optind; /* * Process command line arguments. */ for (optind = 0; optind < argv.length; optind++) { if (argv[optind].equals("-T")) { protocol = argv[++optind]; } else if (argv[optind].equals("-H")) { host = argv[++optind]; } else if (argv[optind].equals("-U")) { user = argv[++optind]; } else if (argv[optind].equals("-P")) { password = argv[++optind]; } else if (argv[optind].equals("-M")) { mailhost = argv[++optind]; } else if (argv[optind].equals("-f")) { record = argv[++optind]; } else if (argv[optind].equals("-a")) { file = argv[++optind]; } else if (argv[optind].equals("-s")) { subject = argv[++optind]; } else if (argv[optind].equals("-o")) { // originator from = argv[++optind]; } else if (argv[optind].equals("-c")) { cc = argv[++optind]; } else if (argv[optind].equals("-b")) { bcc = argv[++optind]; } else if (argv[optind].equals("-L")) { url = argv[++optind]; } else if (argv[optind].equals("-d")) { debug = true; } else if (argv[optind].equals("-v")) { verbose = true; } else if (argv[optind].equals("-A")) { auth = true; } else if (argv[optind].equals("-S")) { prot = "smtps"; } else if (argv[optind].equals("--")) { optind++; break; } else if (argv[optind].startsWith("-")) { System.out.println("Usage: smtpsend [[-L store-url] | [-T prot] [-H host] [-U user] [-P passwd]]"); System.out.println("\t[-s subject] [-o from-address] [-c cc-addresses] [-b bcc-addresses]"); System.out.println("\t[-f record-mailbox] [-M transport-host] [-d] [-a attach-file]"); System.out.println("\t[-v] [-A] [-S] [address]"); System.exit(1); } else { break; } } try { /* * Prompt for To and Subject, if not specified. */ if (optind < argv.length) { // XXX - concatenate all remaining arguments to = argv[optind]; System.out.println("To: " + to); } else { System.out.print("To: "); System.out.flush(); to = in.readLine(); } if (subject == null) { System.out.print("Subject: "); System.out.flush(); subject = in.readLine(); } else { System.out.println("Subject: " + subject); } /* * Initialize the JavaMail Session. */ Properties props = System.getProperties(); if (mailhost != null) props.put("mail." + prot + ".host", mailhost); if (auth) props.put("mail." + prot + ".auth", "true"); /* * Create a Provider representing our extended SMTP transport * and set the property to use our provider. * Provider p = new Provider(Provider.Type.TRANSPORT, prot, "smtpsend$SMTPExtension", "JavaMail demo", "no version"); props.put("mail." + prot + ".class", "smtpsend$SMTPExtension"); */ // Get a Session object Session session = Session.getInstance(props, null); if (debug) session.setDebug(true); /* * Register our extended SMTP transport. * session.addProvider(p); */ /* * Construct the message and send it. */ Message msg = new MimeMessage(session); if (from != null) msg.setFrom(new InternetAddress(from)); else msg.setFrom(); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); if (cc != null) msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); if (bcc != null) msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); msg.setSubject(subject); String text = collect(in); if (file != null) { // Attach the specified file. // We need a multipart message to hold the attachment. MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(text); MimeBodyPart mbp2 = new MimeBodyPart(); mbp2.attachFile(file); MimeMultipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); mp.addBodyPart(mbp2); msg.setContent(mp); } else { // If the desired charset is known, you can use // setText(text, charset) msg.setText(text); } msg.setHeader("X-Mailer", mailer); msg.setSentDate(new Date()); // send the thing off /* * The simple way to send a message is this: * Transport.send(msg); * * But we're going to use some SMTP-specific features for * demonstration purposes so we need to manage the Transport * object explicitly. */ SMTPTransport t = (SMTPTransport) session.getTransport(prot); try { if (auth) t.connect(mailhost, user, password); else t.connect(); t.sendMessage(msg, msg.getAllRecipients()); } finally { if (verbose) System.out.println("Response: " + t.getLastServerResponse()); t.close(); } System.out.println("\nMail was sent successfully."); /* * Save a copy of the message, if requested. */ if (record != null) { // Get a Store object Store store = null; if (url != null) { URLName urln = new URLName(url); store = session.getStore(urln); store.connect(); } else { if (protocol != null) store = session.getStore(protocol); else store = session.getStore(); // Connect if (host != null || user != null || password != null) store.connect(host, user, password); else store.connect(); } // Get record Folder. Create if it does not exist. Folder folder = store.getFolder(record); if (folder == null) { System.err.println("Can't get record folder."); System.exit(1); } if (!folder.exists()) folder.create(Folder.HOLDS_MESSAGES); Message[] msgs = new Message[1]; msgs[0] = msg; folder.appendMessages(msgs); System.out.println("Mail was recorded successfully."); } } catch (Exception e) { /* * Handle SMTP-specific exceptions. */ if (e instanceof SendFailedException) { MessagingException sfe = (MessagingException) e; if (sfe instanceof SMTPSendFailedException) { SMTPSendFailedException ssfe = (SMTPSendFailedException) sfe; System.out.println("SMTP SEND FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else { if (verbose) System.out.println("Send failed: " + sfe.toString()); } Exception ne; while ((ne = sfe.getNextException()) != null && ne instanceof MessagingException) { sfe = (MessagingException) ne; if (sfe instanceof SMTPAddressFailedException) { SMTPAddressFailedException ssfe = (SMTPAddressFailedException) sfe; System.out.println("ADDRESS FAILED:"); if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } else if (sfe instanceof SMTPAddressSucceededException) { System.out.println("ADDRESS SUCCEEDED:"); SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) sfe; if (verbose) System.out.println(ssfe.toString()); System.out.println(" Address: " + ssfe.getAddress()); System.out.println(" Command: " + ssfe.getCommand()); System.out.println(" RetCode: " + ssfe.getReturnCode()); System.out.println(" Response: " + ssfe.getMessage()); } } } else { System.out.println("Got Exception: " + e); if (verbose) e.printStackTrace(); } } }
From source file:com.mgmtp.jfunk.core.mail.MessagePredicates.java
/** * Creates a {@link Predicate} for matching a mail recipient. This Predicate returns true if at least * one recipient matches the given value. * /* ww w . j a v a 2s . co m*/ * @param recipient * the recipient to match * @return the predicate */ public static Predicate<Message> forRecipient(final String recipient) { return new Predicate<Message>() { @Override public boolean apply(final Message input) { Address[] addresses; try { addresses = input.getAllRecipients(); if (addresses == null) { return false; } for (Address address : addresses) { if (StringUtils.equalsIgnoreCase(address.toString(), recipient)) { return true; } } } catch (MessagingException e) { throw new MailException("Error while reading recipients", e); } return false; } @Override public String toString() { return String.format("recipient to include %s", recipient); } }; }
From source file:com.liferay.util.mail.MailEngine.java
private static void _sendMessage(Session session, Message msg) throws MessagingException { boolean smtpAuth = GetterUtil.getBoolean(session.getProperty("mail.smtp.auth"), false); String smtpHost = session.getProperty("mail.smtp.host"); String user = session.getProperty("mail.smtp.user"); String password = session.getProperty("mail.smtp.password"); if (smtpAuth && Validator.isNotNull(user) && Validator.isNotNull(password)) { Transport tr = session.getTransport("smtp"); tr.connect(smtpHost, user, password); tr.sendMessage(msg, msg.getAllRecipients()); tr.close();//from w w w. j a v a 2 s . c o m } else { Transport.send(msg); } }
From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * Send the message//from w w w . ja v a 2 s. c o m * * @param msg * the message to send * @param transport * the transport used to send the message * @throws MessagingException * If a messaging error occured * @throws AddressException * If invalid address */ private static void sendMessage(Message msg, Transport transport) throws MessagingException, AddressException { if (msg.getAllRecipients() != null) { // Send the message transport.sendMessage(msg, msg.getAllRecipients()); } else { throw new AddressException("Mail adress is null"); } }
From source file:dk.netarkivet.common.utils.EMailUtils.java
/** * Send an email, possibly forgiving errors. * * @param to The recipient of the email. Separate multiple recipients with * commas. Supports only adresses of the type 'john@doe.dk', not * 'John Doe <john@doe.dk>' * @param from The sender of the email./*from ww w . j a va 2 s. c o m*/ * @param subject The subject of the email. * @param body The body of the email. * @param forgive On true, will send the email even on invalid email * addresses, if at least one recipient can be set, on false, will * throw exceptions on any invalid email address. * * * @throws ArgumentNotValid If either parameter is null, if to, from or * subject is the empty string, or no recipient * can be set. If "forgive" is false, also on * any invalid to or from address. * @throws IOFailure If the message cannot be sent for some reason. */ public static void sendEmail(String to, String from, String subject, String body, boolean forgive) { ArgumentNotValid.checkNotNullOrEmpty(to, "String to"); ArgumentNotValid.checkNotNullOrEmpty(from, "String from"); ArgumentNotValid.checkNotNullOrEmpty(subject, "String subject"); ArgumentNotValid.checkNotNull(body, "String body"); Properties props = new Properties(); props.put(MAIL_FROM_PROPERTY_KEY, from); props.put(MAIL_HOST_PROPERTY_KEY, Settings.get(CommonSettings.MAIL_SERVER)); Session session = Session.getDefaultInstance(props); Message msg = new MimeMessage(session); // to might contain more than one e-mail address for (String toAddressS : to.split(",")) { try { InternetAddress toAddress = new InternetAddress(toAddressS.trim()); msg.addRecipient(Message.RecipientType.TO, toAddress); } catch (AddressException e) { if (forgive) { log.warn("To address '" + toAddressS + "' is not a valid email " + "address", e); } else { throw new ArgumentNotValid("To address '" + toAddressS + "' is not a valid email " + "address", e); } } catch (MessagingException e) { if (forgive) { log.warn("To address '" + toAddressS + "' could not be set in email", e); } else { throw new ArgumentNotValid("To address '" + toAddressS + "' could not be set in email", e); } } } try { if (msg.getAllRecipients().length == 0) { throw new ArgumentNotValid("No valid recipients in '" + to + "'"); } } catch (MessagingException e) { throw new ArgumentNotValid("Message invalid after setting" + " recipients", e); } try { InternetAddress fromAddress = null; fromAddress = new InternetAddress(from); msg.setFrom(fromAddress); } catch (AddressException e) { throw new ArgumentNotValid("From address '" + from + "' is not a valid email " + "address", e); } catch (MessagingException e) { if (forgive) { log.warn("From address '" + from + "' could not be set in email", e); } else { throw new ArgumentNotValid("From address '" + from + "' could not be set in email", e); } } try { msg.setSubject(subject); msg.setContent(body, MIMETYPE); msg.setSentDate(new Date()); Transport.send(msg); } catch (MessagingException e) { throw new IOFailure("Could not send email with subject '" + subject + "' from '" + from + "' to '" + to + "'. Body:\n" + body, e); } }
From source file:com.intuit.tank.mail.TankMailer.java
private void logMsg(String host, Message m) { try {/* w ww .ja v a2 s. co m*/ StringBuilder sb = new StringBuilder(); sb.append("To: ").append(StringUtils.join(m.getAllRecipients(), ',')).append('\n'); sb.append("From: ").append(StringUtils.join(m.getFrom(), ',')).append('\n'); sb.append("Subject: ").append(m.getSubject()).append('\n'); sb.append("Body: ").append(m.getContent()).append('\n'); LOG.info("Sending email to server (" + host + "):\n" + sb.toString()); } catch (Exception e) { LOG.error("Error generating log msg: " + e); } }
From source file:hudson.maven.reporters.MavenMailerTest.java
/** * Test using the list of recipients of TAG ciManagement defined in * ModuleRoot for all the modules.//from ww w . j a va2s . c o m * * @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:hudson.maven.reporters.MavenMailerTest.java
/** * Test using the list of recipients of TAG ciManagement defined in * ModuleRoot for de root module, and the recipients defined in moduleA for * moduleA./*from w w w.ja va 2 s. com*/ * * @throws Exception */ @Test @Bug(6421) public void testCiManagementNotificationModule() throws Exception { JenkinsLocationConfiguration.get().setAdminAddress(EMAIL_ADMIN); Mailbox otherInbox = Mailbox.get(new InternetAddress(EMAIL_OTHER)); Mailbox someInbox = Mailbox.get(new InternetAddress(EMAIL_SOME)); Mailbox jenkinsConfiguredInbox = Mailbox.get(new InternetAddress(EMAIL_JENKINS_CONFIGURED)); otherInbox.clear(); someInbox.clear(); jenkinsConfiguredInbox.clear(); j.configureDefaultMaven(); MavenModuleSet mms = j.createMavenProject(); mms.setGoals("test"); mms.setScm(new ExtractResourceSCM(getClass().getResource("/hudson/maven/JENKINS-1201-module-defined.zip"))); MavenMailer m = new MavenMailer(); m.recipients = EMAIL_JENKINS_CONFIGURED; m.perModuleEmail = true; mms.getReporters().add(m); j.assertBuildStatus(Result.FAILURE, mms.scheduleBuild2(0).get()); assertEquals(1, otherInbox.size()); assertEquals(1, someInbox.size()); assertEquals(2, jenkinsConfiguredInbox.size()); Message message = otherInbox.get(0); assertEquals(2, message.getAllRecipients().length); assertContainsRecipient(EMAIL_OTHER, message); assertContainsRecipient(EMAIL_JENKINS_CONFIGURED, message); message = someInbox.get(0); 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_JENKINS_CONFIGURED, message); message = jenkinsConfiguredInbox.get(1); assertEquals(2, message.getAllRecipients().length); assertContainsRecipient(EMAIL_JENKINS_CONFIGURED, message); }