List of usage examples for javax.mail.internet InternetAddress toString
public static String toString(Address[] addresses)
From source file:MainClass.java
public static void main(String[] args) throws Exception { URLName server = new URLName("protocol://username@host/foldername"); Session session = Session.getDefaultInstance(new Properties(), new MailAuthenticator()); Folder folder = session.getFolder(server); if (folder == null) { System.out.println("Folder " + server.getFile() + " not found."); System.exit(1);/*from w w w.ja va 2 s . c o m*/ } folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { System.out.println("Message " + (i + 1)); System.out.println("From: " + InternetAddress.toString(messages[i].getFrom())); System.out.println("Reply-to: " + InternetAddress.toString(messages[i].getReplyTo())); String to = InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.TO)); System.out.println("To: " + to); String cc = InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.CC)); System.out.println("Cc: " + cc); String bcc = InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.BCC)); System.out.println("Bcc: " + bcc); System.out.println("Subject: " + messages[i].getSubject()); System.out.println("Sent: " + messages[i].getSentDate()); System.out.println("Received: " + messages[i].getReceivedDate()); } folder.close(false); }
From source file:Main.java
public static void main(String[] args) throws Exception { URLName server = new URLName("protocol://username@host/foldername"); Session session = Session.getDefaultInstance(new Properties(), new MailAuthenticator()); Folder folder = session.getFolder(server); if (folder == null) { System.out.println("Folder " + server.getFile() + " not found."); System.exit(1);/*from www. j a v a 2 s. com*/ } folder.open(Folder.READ_ONLY); Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { System.out.println("From: " + InternetAddress.toString(messages[i].getFrom())); System.out.println("Reply-to: " + InternetAddress.toString(messages[i].getReplyTo())); System.out.println( "To: " + InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.TO))); System.out.println( "Cc: " + InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.CC))); System.out.println( "Bcc: " + InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.BCC))); System.out.println("Subject: " + messages[i].getSubject()); System.out.println("Sent: " + messages[i].getSentDate()); System.out.println("Received: " + messages[i].getReceivedDate()); if (messages[i].isSet(Flags.Flag.DELETED)) { System.out.println("Deleted"); } if (messages[i].isSet(Flags.Flag.ANSWERED)) { System.out.println("Answered"); } if (messages[i].isSet(Flags.Flag.DRAFT)) { System.out.println("Draft"); } if (messages[i].isSet(Flags.Flag.FLAGGED)) { System.out.println("Marked"); } if (messages[i].isSet(Flags.Flag.RECENT)) { System.out.println("Recent"); } if (messages[i].isSet(Flags.Flag.SEEN)) { System.out.println("Read"); } if (messages[i].isSet(Flags.Flag.USER)) { // We don't know what the user flags might be in advance // so they're returned as an array of strings String[] userFlags = messages[i].getFlags().getUserFlags(); for (int j = 0; j < userFlags.length; j++) { System.out.println("User flag: " + userFlags[j]); } } } folder.close(false); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { URLName server = new URLName("protocol://username@host/foldername"); Session session = Session.getDefaultInstance(new Properties(), new MailAuthenticator()); Folder folder = session.getFolder(server); if (folder == null) { System.out.println("Folder " + server.getFile() + " not found."); System.exit(1);/*from ww w . j a v a2 s. co m*/ } folder.open(Folder.READ_ONLY); // Get the messages from the server Message[] messages = folder.getMessages(); for (int i = 0; i < messages.length; i++) { // Get the headers System.out.println("From: " + InternetAddress.toString(messages[i].getFrom())); System.out.println("Reply-to: " + InternetAddress.toString(messages[i].getReplyTo())); System.out.println( "To: " + InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.TO))); System.out.println( "Cc: " + InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.CC))); System.out.println( "Bcc: " + InternetAddress.toString(messages[i].getRecipients(Message.RecipientType.BCC))); System.out.println("Subject: " + messages[i].getSubject()); System.out.println("Sent: " + messages[i].getSentDate()); System.out.println("Received: " + messages[i].getReceivedDate()); if (messages[i].isSet(Flags.Flag.DELETED)) { System.out.println("Deleted"); } if (messages[i].isSet(Flags.Flag.ANSWERED)) { System.out.println("Answered"); } if (messages[i].isSet(Flags.Flag.DRAFT)) { System.out.println("Draft"); } if (messages[i].isSet(Flags.Flag.FLAGGED)) { System.out.println("Marked"); } if (messages[i].isSet(Flags.Flag.RECENT)) { System.out.println("Recent"); } if (messages[i].isSet(Flags.Flag.SEEN)) { System.out.println("Read"); } if (messages[i].isSet(Flags.Flag.USER)) { // We don't know what the user flags might be in advance // so they're returned as an array of strings String[] userFlags = messages[i].getFlags().getUserFlags(); for (int j = 0; j < userFlags.length; j++) { System.out.println("User flag: " + userFlags[j]); } } } folder.close(false); }
From source file:es.ucm.fdi.dalgs.mailbox.service.MailBoxService.java
/** * Returns new messages and fetches details for each message. *//*from ww w. ja va 2 s . co m*/ @Transactional(readOnly = false) public ResultClass<Boolean> downloadEmails() { ResultClass<Boolean> result = new ResultClass<>(); Properties properties = getServerProperties(protocol, host, port); Session session = Session.getDefaultInstance(properties); try { // connects to the message store Store store = session.getStore(protocol); store.connect(userName, password); // opens the inbox folder Folder folderInbox = store.getFolder("INBOX"); folderInbox.open(Folder.READ_ONLY); // fetches new messages from server Message[] messages = folderInbox.getMessages(); for (int i = 0; i < messages.length; i++) { Message msg = messages[i]; String[] idHeaders = msg.getHeader("MESSAGE-ID"); if (idHeaders != null && idHeaders.length > 0) { MessageBox exists = repositoryMailBox.getMessageBox(idHeaders[0]); if (exists == null) { MessageBox messageBox = new MessageBox(); messageBox.setSubject(msg.getSubject()); messageBox.setCode(idHeaders[0]); Address[] fromAddresses = msg.getFrom(); String from = InternetAddress.toString(fromAddresses); if (from.startsWith("=?")) { from = MimeUtility.decodeWord(from); } messageBox.setFrom(from); String to = InternetAddress.toString(msg.getRecipients(RecipientType.TO)); if (to.startsWith("=?")) { to = MimeUtility.decodeWord(to); } messageBox.setTo(to); String[] replyHeaders = msg.getHeader("References"); if (replyHeaders != null && replyHeaders.length > 0) { StringTokenizer tokens = new StringTokenizer(replyHeaders[0]); MessageBox parent = repositoryMailBox.getMessageBox(tokens.nextToken()); if (parent != null) parent.addReply(messageBox); } result = parseSubjectAndCreate(messageBox, msg); } } } folderInbox.close(false); store.close(); return result; } catch (NoSuchProviderException ex) { logger.error("No provider for protocol: " + protocol); ex.printStackTrace(); } catch (MessagingException ex) { logger.error("Could not connect to the message store"); ex.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } result.setSingleElement(false); return result; }
From source file:immf.ImodeForwardMail.java
@Override public void buildMimeMessage() throws EmailException { super.buildMimeMessage(); MimeMessage msg = this.getMimeMessage(); try {/* w w w. jav a2s . c o m*/ msg.setHeader("X-Mailer", ServerMain.Version); if (!this.conf.isRewriteAddress()) { // ??imode???????? msg.setHeader("Resent-From", this.conf.getSmtpMailAddress()); if (!this.conf.getForwardTo().isEmpty()) { msg.setHeader("Resent-To", StringUtils.join(this.conf.getForwardTo(), ",")); } if (!this.conf.getForwardCc().isEmpty()) { msg.setHeader("Resent-Cc", StringUtils.join(this.conf.getForwardCc(), ",")); } if (!this.conf.getForwardBcc().isEmpty()) { msg.setHeader("Resent-Bcc", StringUtils.join(this.conf.getForwardBcc(), ",")); } SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z (z)", Locale.US); msg.setHeader("Resent-Date", df.format(new Date())); msg.setHeader("Date", df.format(this.imm.getTimeDate())); msg.removeHeader("To"); msg.removeHeader("Cc"); msg.removeHeader("Bcc"); List<InternetAddress> tolist = new ArrayList<InternetAddress>(); List<InternetAddress> cclist = new ArrayList<InternetAddress>(); boolean useMyAddress = false; if (this.imm.getFolderId() != ImodeNetClient.FolderIdSent) { if (this.conf.isHideMyaddr()) { if (this.imm.getToAddrList().size() == 0) { useMyAddress = true; } } else { useMyAddress = true; } } if (useMyAddress) { switch (this.imm.getRecvType()) { case ImodeMail.RECV_TYPE_TO: tolist.add(this.imm.getMyInternetAddress()); break; case ImodeMail.RECV_TYPE_CC: cclist.add(this.imm.getMyInternetAddress()); break; case ImodeMail.RECV_TYPE_BCC: break; } } tolist.addAll(this.imm.getToAddrList()); cclist.addAll(this.imm.getCcAddrList()); msg.setHeader("To", InternetAddress.toString(tolist.toArray(new InternetAddress[0]))); if (this.imm.getCcAddrList().size() > 0) { msg.setHeader("Cc", InternetAddress.toString(cclist.toArray(new InternetAddress[0]))); } msg.setFrom(this.imm.getFromAddr()); } String subject = null; if (imm.getFolderId() == ImodeNetClient.FolderIdSent) { subject = conf.getSentSubjectAppendPrefix() + imm.getSubject() + conf.getSentSubjectAppendSuffix(); } else { subject = conf.getSubjectAppendPrefix() + imm.getSubject() + conf.getSubjectAppendSuffix(); } if (conf.isSubjectEmojiReplace()) { subject = EmojiUtil.replaceToLabel(subject); } if (ImodeForwardMail.goomojiSubjectCharConv != null) { String goomojiSubject = ImodeForwardMail.goomojiSubjectCharConv.convert(subject); msg.setHeader("X-Goomoji-Source", "docomo_ne_jp"); msg.setHeader("X-Goomoji-Subject", Util.encodeGoomojiSubject(goomojiSubject)); } subject = ImodeForwardMail.subjectCharConv.convert(subject); msg.setSubject(MimeUtility.encodeText(subject, this.charset, "B")); if (this.conf.getContentTransferEncoding() != null) { msg.setHeader("Content-Transfer-Encoding", this.conf.getContentTransferEncoding()); } } catch (Exception e) { log.warn(e); } }
From source file:org.apache.axis2.transport.mail.MailTransportSender.java
/** * Populate email with a SOAP formatted message * @param outInfo the out transport information holder * @param msgContext the message context that holds the message to be written * @throws AxisFault on error//from www.j av a 2s . c om * @return id of the send mail message */ private String sendMail(MailOutTransportInfo outInfo, MessageContext msgContext) throws AxisFault, MessagingException, IOException { OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext); // Make sure that non textual attachements are sent with base64 transfer encoding // instead of binary. format.setProperty(OMOutputFormat.USE_CTE_BASE64_FOR_NON_TEXTUAL_ATTACHMENTS, true); MessageFormatter messageFormatter = BaseUtils.getMessageFormatter(msgContext); if (log.isDebugEnabled()) { log.debug( "Creating MIME message using message formatter " + messageFormatter.getClass().getSimpleName()); } WSMimeMessage message = null; if (outInfo.getFromAddress() != null) { message = new WSMimeMessage(session, outInfo.getFromAddress().getAddress()); } else { message = new WSMimeMessage(session, ""); } Map trpHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); if (log.isDebugEnabled() && trpHeaders != null) { log.debug("Using transport headers: " + trpHeaders); } // set From address - first check if this is a reply, then use from address from the // transport out, else if any custom transport headers set on this message, or default // to the transport senders default From address if (outInfo.getTargetAddresses() != null && outInfo.getFromAddress() != null) { if (log.isDebugEnabled()) { log.debug("Setting From header to " + outInfo.getFromAddress().getAddress() + " from OutTransportInfo"); } message.setFrom(outInfo.getFromAddress()); message.setReplyTo((new Address[] { outInfo.getFromAddress() })); } else if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_FROM)) { InternetAddress from = new InternetAddress((String) trpHeaders.get(MailConstants.MAIL_HEADER_FROM)); if (log.isDebugEnabled()) { log.debug("Setting From header to " + from.getAddress() + " from transport headers"); } message.setFrom(from); message.setReplyTo(new Address[] { from }); } else { if (smtpFromAddress != null) { if (log.isDebugEnabled()) { log.debug("Setting From header to " + smtpFromAddress.getAddress() + " from transport configuration"); } message.setFrom(smtpFromAddress); message.setReplyTo(new Address[] { smtpFromAddress }); } else { handleException("From address for outgoing message cannot be determined"); } } // set To address/es to any custom transport header set on the message, else use the reply // address from the out transport information if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_TO)) { Address[] to = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_TO)); if (log.isDebugEnabled()) { log.debug("Setting To header to " + InternetAddress.toString(to) + " from transport headers"); } message.setRecipients(Message.RecipientType.TO, to); } else if (outInfo.getTargetAddresses() != null) { if (log.isDebugEnabled()) { log.debug("Setting To header to " + InternetAddress.toString(outInfo.getTargetAddresses()) + " from OutTransportInfo"); } message.setRecipients(Message.RecipientType.TO, outInfo.getTargetAddresses()); } else { handleException("To address for outgoing message cannot be determined"); } // set Cc address/es to any custom transport header set on the message, else use the // Cc list from original request message if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_CC)) { Address[] cc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_CC)); if (log.isDebugEnabled()) { log.debug("Setting Cc header to " + InternetAddress.toString(cc) + " from transport headers"); } message.setRecipients(Message.RecipientType.CC, cc); } else if (outInfo.getCcAddresses() != null) { if (log.isDebugEnabled()) { log.debug("Setting Cc header to " + InternetAddress.toString(outInfo.getCcAddresses()) + " from OutTransportInfo"); } message.setRecipients(Message.RecipientType.CC, outInfo.getCcAddresses()); } // set Bcc address/es to any custom addresses set at the transport sender level + any // custom transport header if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_BCC)) { InternetAddress[] bcc = InternetAddress.parse((String) trpHeaders.get(MailConstants.MAIL_HEADER_BCC)); if (log.isDebugEnabled()) { log.debug("Adding Bcc header values " + InternetAddress.toString(bcc) + " from transport headers"); } message.addRecipients(Message.RecipientType.BCC, bcc); } if (smtpBccAddresses != null) { if (log.isDebugEnabled()) { log.debug("Adding Bcc header values " + InternetAddress.toString(smtpBccAddresses) + " from transport configuration"); } message.addRecipients(Message.RecipientType.BCC, smtpBccAddresses); } // set subject if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_SUBJECT)) { if (log.isDebugEnabled()) { log.debug("Setting Subject header to '" + trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT) + "' from transport headers"); } message.setSubject((String) trpHeaders.get(MailConstants.MAIL_HEADER_SUBJECT)); } else if (outInfo.getSubject() != null) { if (log.isDebugEnabled()) { log.debug("Setting Subject header to '" + outInfo.getSubject() + "' from transport headers"); } message.setSubject(outInfo.getSubject()); } else { if (log.isDebugEnabled()) { log.debug("Generating default Subject header from SOAP action"); } message.setSubject(BaseConstants.SOAPACTION + ": " + msgContext.getSoapAction()); } //TODO: use a combined message id for smtp so that it generates a unique id while // being able to support asynchronous communication. // if a custom message id is set, use it // if (msgContext.getMessageID() != null) { // message.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgContext.getMessageID()); // message.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgContext.getMessageID()); // } // if this is a reply, set reference to original message if (outInfo.getRequestMessageID() != null) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, outInfo.getRequestMessageID()); message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, outInfo.getRequestMessageID()); } else { if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_IN_REPLY_TO)) { message.setHeader(MailConstants.MAIL_HEADER_IN_REPLY_TO, (String) trpHeaders.get(MailConstants.MAIL_HEADER_IN_REPLY_TO)); } if (trpHeaders != null && trpHeaders.containsKey(MailConstants.MAIL_HEADER_REFERENCES)) { message.setHeader(MailConstants.MAIL_HEADER_REFERENCES, (String) trpHeaders.get(MailConstants.MAIL_HEADER_REFERENCES)); } } // set Date message.setSentDate(new Date()); // set SOAPAction header message.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); // write body MessageFormatterEx messageFormatterEx; if (messageFormatter instanceof MessageFormatterEx) { messageFormatterEx = (MessageFormatterEx) messageFormatter; } else { messageFormatterEx = new MessageFormatterExAdapter(messageFormatter); } DataHandler dataHandler = new DataHandler( messageFormatterEx.getDataSource(msgContext, format, msgContext.getSoapAction())); MimeMultipart mimeMultiPart = null; String mFormat = (String) msgContext.getProperty(MailConstants.TRANSPORT_MAIL_FORMAT); if (mFormat == null) { mFormat = defaultMailFormat; } if (log.isDebugEnabled()) { log.debug("Using mail format '" + mFormat + "'"); } MimePart mainPart; if (MailConstants.TRANSPORT_FORMAT_MP.equals(mFormat)) { mimeMultiPart = new MimeMultipart(); MimeBodyPart mimeBodyPart1 = new MimeBodyPart(); mimeBodyPart1.setContent("Web Service Message Attached", "text/plain"); MimeBodyPart mimeBodyPart2 = new MimeBodyPart(); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); message.setContent(mimeMultiPart); mainPart = mimeBodyPart2; } else if (MailConstants.TRANSPORT_FORMAT_ATTACHMENT.equals(mFormat)) { mimeMultiPart = new MimeMultipart(); MimeBodyPart mimeBodyPart1 = new MimeBodyPart(); mimeBodyPart1.setContent("Web Service Message Attached", "text/plain"); MimeBodyPart mimeBodyPart2 = new MimeBodyPart(); mimeMultiPart.addBodyPart(mimeBodyPart1); mimeMultiPart.addBodyPart(mimeBodyPart2); message.setContent(mimeMultiPart); String fileName = (String) msgContext.getProperty(MailConstants.TRANSPORT_FORMAT_ATTACHMENT_FILE); if (fileName != null) { mimeBodyPart2.setFileName(fileName); } else { mimeBodyPart2.setFileName("attachment"); } mainPart = mimeBodyPart2; } else { mainPart = message; } try { mainPart.setHeader(BaseConstants.SOAPACTION, msgContext.getSoapAction()); mainPart.setDataHandler(dataHandler); // AXIOM's idea of what is textual also includes application/xml and // application/soap+xml (which JavaMail considers as binary). For these content types // always use quoted-printable transfer encoding. Note that JavaMail is a bit smarter // here because it can choose between 7bit and quoted-printable automatically, but it // needs to scan the entire content to determine this. if (msgContext.getOptions().getProperty("Content-Transfer-Encoding") != null) { mainPart.setHeader("Content-Transfer-Encoding", (String) msgContext.getOptions().getProperty("Content-Transfer-Encoding")); } else { String contentType = dataHandler.getContentType().toLowerCase(); if (!contentType.startsWith("multipart/") && CommonUtils.isTextualPart(contentType)) { mainPart.setHeader("Content-Transfer-Encoding", "quoted-printable"); } } //setting any custom headers defined by the user if (msgContext.getOptions().getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS) != null) { Map customTransportHeaders = (Map) msgContext.getOptions() .getProperty(MailConstants.TRANSPORT_MAIL_CUSTOM_HEADERS); for (Object header : customTransportHeaders.keySet()) { mainPart.setHeader((String) header, (String) customTransportHeaders.get(header)); } } log.debug("Sending message"); Transport.send(message); // update metrics metrics.incrementMessagesSent(msgContext); long bytesSent = message.getBytesSent(); if (bytesSent != -1) { metrics.incrementBytesSent(msgContext, bytesSent); } } catch (MessagingException e) { metrics.incrementFaultsSending(); handleException("Error creating mail message or sending it to the configured server", e); } return message.getMessageID(); }
From source file:org.xwiki.mail.MailStatus.java
/** * Constructor initializing the MailStatus with mandatory fields (message id, batch id and recipients are extracted * from the passed message, the date is set as now and the state is passed). * Also sets the Type if set in the passed message. * * @param batchId the identifier of the batch sending the message * @param message the message for which to construct a status * @param state the state of the referenced mail (ready, failed to send, success) * @since 7.4.1//from w w w . j a va2s. c o m */ public MailStatus(String batchId, ExtendedMimeMessage message, MailState state) { try { setMessageId(message.getUniqueMessageId()); setBatchId(batchId); setType(message.getType()); setRecipients(InternetAddress.toString(message.getAllRecipients())); setState(state); setDate(new Date()); } catch (MessagingException e) { // This should never happen since the implementation for getHeader() never throws an exception (even // though the interface specifies it can) and similarly getAllRecipients() will also never throw an // exception since the only reason would be if an address is malformed but there's a check when setting // it already in the MimeMessage and thus in practice it cannot happen. throw new RuntimeException( String.format("Unexpected exception constructing the Mail Status for state [%s]", state), e); } }