Search in sources :

Example 61 with Address

use of javax.mail.Address in project nhin-d by DirectProject.

the class DefaultMimeXdsTransformer method transform.

/*
     * (non-Javadoc)
     * 
     * @see org.nhindirect.transform.MimeXdsTransformer#transform(javax.mail.internet.MimeMessage)
     */
@Override
public ProvideAndRegisterDocumentSetRequestType transform(MimeMessage mimeMessage) throws TransformationException {
    ProvideAndRegisterDocumentSetRequestType request;
    DirectDocuments documents = new DirectDocuments();
    byte[] xdsDocument = null;
    String xdsMimeType = null;
    FormatCodeEnum xdsFormatCode = null;
    DirectDocumentType documentType = null;
    try {
        Date sentDate = mimeMessage.getSentDate();
        String subject = mimeMessage.getSubject();
        String from = mimeMessage.getFrom()[0].toString();
        Address[] recipients = mimeMessage.getAllRecipients();
        // Plain mail (no attachments)
        if (MimeType.TEXT_PLAIN.matches(mimeMessage.getContentType())) {
            LOGGER.info("Handling plain mail (no attachments) - " + mimeMessage.getContentType());
            // Get the document type
            documentType = DirectDocumentType.lookup(mimeMessage);
            // Get the format code and MIME type
            xdsFormatCode = documentType.getFormatCode();
            xdsMimeType = documentType.getMimeType().getType();
            // Get the contents
            xdsDocument = ((String) mimeMessage.getContent()).getBytes();
            // Add document to the collection of documents
            documents.getDocuments().add(getDocument(sentDate, from, xdsMimeType, xdsFormatCode, xdsDocument, documentType));
            documents.setSubmissionSet(getSubmissionSet(subject, sentDate, from, recipients, xdsDocument, documentType));
        } else // Multipart/mixed (attachments)
        if (MimeType.MULTIPART.matches(mimeMessage.getContentType())) {
            LOGGER.info("Handling multipart/mixed - " + mimeMessage.getContentType());
            MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
            BodyPart xdmBodyPart = null;
            for (int i = 0; i < mimeMultipart.getCount(); i++) {
                //check for XDM
                BodyPart bodyPart = mimeMultipart.getBodyPart(i);
                documentType = DirectDocumentType.lookup(bodyPart);
                if (DirectDocumentType.XDM.equals(documentType)) {
                    xdmBodyPart = bodyPart;
                }
            }
            // For each BodyPart
            for (int i = 0; i < mimeMultipart.getCount(); i++) {
                /*
                     * Special handling for XDM attachments.
                     * 
                     * Spec says if XDM package is present, this will be the
                     * only attachment.
                     * 
                     * Overwrite all documents with XDM content and then break
                     */
                if (xdmBodyPart != null) {
                    XdmPackage xdmPackage = XdmPackage.fromXdmZipDataHandler(xdmBodyPart.getDataHandler());
                    // Spec says if XDM package is present, this will be the only attachment
                    // Overwrite all documents with XDM content and then break
                    System.out.println("XDM FILE FOUND");
                    documents = xdmPackage.getDocuments();
                    break;
                }
                BodyPart bodyPart = mimeMultipart.getBodyPart(i);
                // Skip empty BodyParts
                if (bodyPart.getSize() <= 0) {
                    LOGGER.warn("Empty body, skipping");
                    continue;
                }
                // Get the document type
                documentType = DirectDocumentType.lookup(bodyPart);
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("File name: " + bodyPart.getFileName());
                }
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Content type: " + bodyPart.getContentType());
                }
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("DocumentType: " + documentType.toString());
                }
                // Get the format code and MIME type
                xdsFormatCode = documentType.getFormatCode();
                xdsMimeType = documentType.getMimeType().getType();
                // Best guess for UNKNOWN MIME type
                if (DirectDocumentType.UNKNOWN.equals(documentType)) {
                    xdsMimeType = bodyPart.getContentType();
                }
                // Get the contents
                xdsDocument = read(bodyPart);
                // Add the document to the collection of documents
                documents.getDocuments().add(getDocument(sentDate, from, xdsMimeType, xdsFormatCode, xdsDocument, documentType));
                documents.setSubmissionSet(getSubmissionSet(subject, sentDate, from, recipients, xdsDocument, documentType));
            }
        } else {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("Message content type (" + mimeMessage.getContentType() + ") is not supported, skipping");
            }
        }
    } catch (MessagingException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Unexpected MessagingException occured while handling MimeMessage", e);
        }
        throw new TransformationException("Unable to complete transformation.", e);
    } catch (IOException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Unexpected IOException occured while handling MimeMessage", e);
        }
        throw new TransformationException("Unable to complete transformation.", e);
    } catch (Exception e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Unexpected Exception occured while handling MimeMessage", e);
        }
        throw new TransformationException("Unable to complete transformation", e);
    }
    try {
        request = documents.toProvideAndRegisterDocumentSetRequestType();
    } catch (IOException e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Unexpected IOException occured while transforming to ProvideAndRegisterDocumentSetRequestType", e);
        }
        throw new TransformationException("Unable to complete transformation", e);
    }
    return request;
}
Also used : BodyPart(javax.mail.BodyPart) TransformationException(org.nhindirect.xd.transform.exception.TransformationException) Address(javax.mail.Address) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) Date(java.util.Date) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) TransformationException(org.nhindirect.xd.transform.exception.TransformationException) DirectDocumentType(org.nhindirect.xd.common.type.DirectDocumentType) MimeMultipart(javax.mail.internet.MimeMultipart) DirectDocuments(org.nhindirect.xd.common.DirectDocuments) FormatCodeEnum(org.nhindirect.xd.common.type.FormatCodeEnum) XdmPackage(org.nhindirect.xd.common.XdmPackage) ProvideAndRegisterDocumentSetRequestType(ihe.iti.xds_b._2007.ProvideAndRegisterDocumentSetRequestType)

Example 62 with Address

use of javax.mail.Address in project Axe by DongyuCai.

the class SimpleMailSender method sendTextMail.

/**
	 * 以文本格式发送邮件
	 * 
	 * @param mailInfo
	 *            待发送的邮件的信息
	 */
public static boolean sendTextMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    if (mailInfo.isValidate()) {
        // 如果需要身份认证,则创建一个密码验证器
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // 设置邮件消息的主要内容
        String mailContent = mailInfo.getContent();
        mailMessage.setText(mailContent);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Date(java.util.Date) Session(javax.mail.Session)

Example 63 with Address

use of javax.mail.Address in project nhin-d by DirectProject.

the class DNSGenerator_CreateDSNMessageTest method testCreateDSNMessage_createGeneralDSNMessage.

@Test
public void testCreateDSNMessage_createGeneralDSNMessage() throws Exception {
    final DSNGenerator dsnGenerator = new DSNGenerator("Not Delivered:");
    final DSNRecipientHeaders dsnRecipHeaders = new DSNRecipientHeaders(DSNAction.FAILED, DSNStatus.getStatus(DSNStatus.PERMANENT, DSNStatus.UNDEFINED_STATUS), new InternetAddress("ah4626@test.com"));
    final List<DSNRecipientHeaders> dsnHeaders = new ArrayList<DSNRecipientHeaders>();
    dsnHeaders.add(dsnRecipHeaders);
    final String originalMessageId = UUID.randomUUID().toString();
    final DSNMessageHeaders messageDSNHeaders = new DSNMessageHeaders("DirectJUNIT", originalMessageId, MtaNameType.DNS);
    List<Address> faileRecips = new ArrayList<Address>();
    faileRecips.add(new InternetAddress("ah4626@test.com"));
    final DefaultDSNFailureTextBodyPartGenerator textGenerator = new DefaultDSNFailureTextBodyPartGenerator("", "", "", "", "", HumanReadableTextAssemblerFactory.getInstance());
    final MimeBodyPart textBodyPart = textGenerator.generate(new InternetAddress("gm2552@test.com"), faileRecips, null);
    MimeMessage dsnMessage = dsnGenerator.createDSNMessage(new InternetAddress("gm2552@test.com"), "test", new InternetAddress("postmaster@test.com"), dsnHeaders, messageDSNHeaders, textBodyPart);
    assertNotNull(dsnMessage);
    assertEquals("postmaster@test.com", MailStandard.getHeader(dsnMessage, MailStandard.Headers.From));
    assertEquals("gm2552@test.com", MailStandard.getHeader(dsnMessage, MailStandard.Headers.To));
    assertTrue(MailStandard.getHeader(dsnMessage, MailStandard.Headers.Subject).startsWith("Not Delivered:"));
    assertTrue(!MailStandard.getHeader(dsnMessage, MailStandard.Headers.Date).isEmpty());
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) ArrayList(java.util.ArrayList) DefaultDSNFailureTextBodyPartGenerator(org.nhindirect.common.mail.dsn.impl.DefaultDSNFailureTextBodyPartGenerator) MimeBodyPart(javax.mail.internet.MimeBodyPart) Test(org.junit.Test)

Example 64 with Address

use of javax.mail.Address in project nhin-d by DirectProject.

the class DefaultTxDetailParser method getMessageDetails.

@SuppressWarnings("incomplete-switch")
@Override
public Map<String, TxDetail> getMessageDetails(MimeMessage msg) {
    Map<String, TxDetail> retVal = new HashMap<String, TxDetail>();
    // get the message id
    final String msgId = MailStandard.getHeader(msg, MailStandard.Headers.MessageID);
    if (!msgId.isEmpty())
        retVal.put(TxDetailType.MSG_ID.getType(), new TxDetail(TxDetailType.MSG_ID.getType(), msgId));
    // get the subject
    final String subject = MailStandard.getHeader(msg, MailStandard.Headers.Subject);
    if (!subject.isEmpty())
        retVal.put(TxDetailType.SUBJECT.getType(), new TxDetail(TxDetailType.SUBJECT.getType(), subject));
    // get the full headers as a string
    final String fullHeaders = getHeadersAsStringInternal(msg);
    if (!fullHeaders.isEmpty())
        retVal.put(TxDetailType.MSG_FULL_HEADERS.getType(), new TxDetail(TxDetailType.MSG_FULL_HEADERS.getType(), fullHeaders));
    // get the from addresses
    try {
        final String from = MailStandard.getHeader(msg, MailStandard.Headers.From);
        if (!from.isEmpty()) {
            StringBuilder builder = new StringBuilder();
            int cnt = 0;
            for (InternetAddress addr : (InternetAddress[]) msg.getFrom()) {
                // comma delimit multiple addresses
                if (cnt > 0)
                    builder.append(",");
                builder.append(addr.getAddress().toLowerCase(Locale.getDefault()));
                ++cnt;
            }
            retVal.put(TxDetailType.FROM.getType(), new TxDetail(TxDetailType.FROM.getType(), builder.toString()));
        }
    }/// CLOVER:OFF
     catch (MessagingException e) {
        LOGGER.warn("Failed to retrieve message sender list.", e);
    }
    // get the sender if it exists
    try {
        final InternetAddress sender = (InternetAddress) msg.getSender();
        if (sender != null)
            retVal.put(TxDetailType.SENDER.getType(), new TxDetail(TxDetailType.SENDER.toString(), sender.getAddress().toLowerCase(Locale.getDefault())));
    }/// CLOVER:OFF
     catch (MessagingException e) {
        LOGGER.warn("Failed to retrieve message sender", e);
    }
    // get the recipient addresses
    try {
        if (msg.getAllRecipients() != null) {
            StringBuilder builder = new StringBuilder();
            int cnt = 0;
            for (Address addr : msg.getAllRecipients()) {
                // comma delimit multiple addresses
                if (cnt > 0)
                    builder.append(",");
                if (addr instanceof InternetAddress)
                    builder.append(((InternetAddress) addr).getAddress().toLowerCase(Locale.getDefault()));
                ++cnt;
            }
            retVal.put(TxDetailType.RECIPIENTS.getType(), new TxDetail(TxDetailType.RECIPIENTS.getType(), builder.toString()));
        }
    }/// CLOVER:OFF
     catch (MessagingException e) {
        LOGGER.warn("Failed to retrieve message recipient list.", e);
    }
    /// CLOVER:ON
    // get the message type
    final TxMessageType messageType = TxUtil.getMessageType(msg);
    if (messageType != TxMessageType.UNKNOWN) {
        switch(messageType) {
            case MDN:
                {
                    // the disposition if a field in the second part of the MDN message
                    final String disposition = MDNStandard.getMDNField(msg, MDNStandard.Headers.Disposition);
                    if (!disposition.isEmpty())
                        retVal.put(TxDetailType.DISPOSITION.getType(), new TxDetail(TxDetailType.DISPOSITION.getType(), disposition.toLowerCase(Locale.getDefault())));
                    // the final recipients is a field in the second part of the MDN message
                    final String finalRecipient = MDNStandard.getMDNField(msg, MDNStandard.Headers.FinalRecipient);
                    if (!finalRecipient.isEmpty())
                        retVal.put(TxDetailType.FINAL_RECIPIENTS.getType(), new TxDetail(TxDetailType.FINAL_RECIPIENTS.getType(), finalRecipient.toLowerCase(Locale.getDefault())));
                    // the original message id if a field in the second part of the MDN message
                    String origMsgId = MDNStandard.getMDNField(msg, MDNStandard.Headers.OriginalMessageID);
                    if (origMsgId.isEmpty()) {
                        // it might be in a reply to header
                        origMsgId = MailStandard.getHeader(msg, MailStandard.Headers.InReplyTo);
                    }
                    if (!origMsgId.isEmpty())
                        retVal.put(TxDetailType.PARENT_MSG_ID.getType(), new TxDetail(TxDetailType.PARENT_MSG_ID.getType(), origMsgId));
                    // check for X-DIRECT-FINAL-DESTINATION-DELIVER extension
                    try {
                        final InternetHeaders mdnHeaders = MDNStandard.getNotificationFieldsAsHeaders(msg);
                        if (mdnHeaders.getHeader(MDNStandard.DispositionOption_TimelyAndReliable, ",") != null) {
                            retVal.put(TxDetailType.DISPOSITION_OPTIONS.getType(), new TxDetail(TxDetailType.DISPOSITION_OPTIONS.getType(), MDNStandard.DispositionOption_TimelyAndReliable));
                        }
                    }// CLOVER:OFF
                     catch (Exception e) {
                        LOGGER.warn("Failed to retrieve MDN headers from message.  Message may not be an MDN message.", e);
                    }
                    // CLOVER:ON
                    break;
                }
            case DSN:
                {
                    // the Original-Envelope-ID header does not reflect the message id
                    try {
                        final DeliveryStatus status = new DeliveryStatus(new ByteArrayInputStream(MailUtil.serializeToBytes(msg)));
                        retVal.put(TxDetailType.FINAL_RECIPIENTS.getType(), new TxDetail(TxDetailType.FINAL_RECIPIENTS.getType(), DSNStandard.getFinalRecipients(status).toLowerCase(Locale.getDefault())));
                        // check at the message level
                        boolean parentFound = false;
                        final String origMsgId = DSNStandard.getHeaderValueFromDeliveryStatus(status, DSNStandard.Headers.OriginalMessageID);
                        if (!origMsgId.isEmpty()) {
                            parentFound = true;
                            retVal.put(TxDetailType.PARENT_MSG_ID.getType(), new TxDetail(TxDetailType.PARENT_MSG_ID, origMsgId));
                        }
                        if (!parentFound) {
                            // it might be in a reply to header
                            final String parentMsgId = MailStandard.getHeader(msg, MailStandard.Headers.InReplyTo);
                            if (!parentMsgId.isEmpty())
                                retVal.put(TxDetailType.PARENT_MSG_ID.getType(), new TxDetail(TxDetailType.PARENT_MSG_ID.getType(), parentMsgId));
                        }
                        // get the action
                        final String action = DSNStandard.getHeaderValueFromDeliveryStatus(status, DSNStandard.Headers.Action);
                        if (!action.isEmpty())
                            retVal.put(TxDetailType.DSN_ACTION.getType(), new TxDetail(TxDetailType.DSN_ACTION.getType(), action.toLowerCase(Locale.getDefault())));
                        // get the status
                        final String dsnStatus = DSNStandard.getHeaderValueFromDeliveryStatus(status, DSNStandard.Headers.Status);
                        if (!dsnStatus.isEmpty())
                            retVal.put(TxDetailType.DSN_STATUS.getType(), new TxDetail(TxDetailType.DSN_STATUS.getType(), dsnStatus.toLowerCase(Locale.getDefault())));
                    }///CLOVER:OFF
                     catch (Exception e) {
                        LOGGER.warn("Could not get a requested field from the DSN message", e);
                    }
                    ///CLOVER:ON
                    break;
                }
        }
    }
    // check for the existence of disposition request options
    final String dispOption = MailStandard.getHeader(msg, MDNStandard.Headers.DispositionNotificationOptions);
    if (!dispOption.isEmpty())
        retVal.put(TxDetailType.DISPOSITION_OPTIONS.getType(), new TxDetail(TxDetailType.DISPOSITION_OPTIONS.getType(), dispOption.toLowerCase(Locale.getDefault())));
    return retVal;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) InternetHeaders(javax.mail.internet.InternetHeaders) HashMap(java.util.HashMap) MessagingException(javax.mail.MessagingException) TxDetail(org.nhindirect.common.tx.model.TxDetail) MessagingException(javax.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream) DeliveryStatus(com.sun.mail.dsn.DeliveryStatus) TxMessageType(org.nhindirect.common.tx.model.TxMessageType)

Example 65 with Address

use of javax.mail.Address in project nhin-d by DirectProject.

the class DSNGenerator method createDeliveryStatus.

/**
	 * Creates the deliver status section of the message
	 * @param recipientDSNHeaders
	 * @param messageDSNHeaders
	 * @return
	 * @throws MessagingException
	 */
protected DeliveryStatus createDeliveryStatus(List<DSNRecipientHeaders> recipientDSNHeaders, DSNMessageHeaders messageDSNHeaders) throws MessagingException {
    final DeliveryStatus deliveryStatus = new DeliveryStatus();
    for (DSNRecipientHeaders dsnHeaders : recipientDSNHeaders) {
        final InternetHeaders recipHeaders = new InternetHeaders();
        final DSNAction dsnAction = dsnHeaders.getAction();
        recipHeaders.addHeader(DSNStandard.Headers.Action, "" + dsnAction);
        final Address finalRecipient = dsnHeaders.getFinalRecipient();
        if (finalRecipient != null) {
            recipHeaders.addHeader(DSNStandard.Headers.FinalRecipient, finalRecipient.getType() + ";" + finalRecipient.toString());
        }
        String status = dsnHeaders.getStatus();
        recipHeaders.addHeader(DSNStandard.Headers.Status, status);
        deliveryStatus.addRecipientDSN(recipHeaders);
    }
    final InternetHeaders messageHeaders = new InternetHeaders();
    final MtaNameType mtaNameType = messageDSNHeaders.getMtaNameType();
    final String reportingMta = messageDSNHeaders.getReportingMta();
    messageHeaders.addHeader(DSNStandard.Headers.ReportingMTA, mtaNameType + ";" + reportingMta);
    // add a custom header with original message id
    final String originalMessageId = messageDSNHeaders.getOriginalMessageId();
    messageHeaders.addHeader(DSNStandard.Headers.OriginalMessageID, originalMessageId);
    deliveryStatus.setMessageDSN(messageHeaders);
    return deliveryStatus;
}
Also used : MtaNameType(org.nhindirect.common.mail.dsn.DSNStandard.MtaNameType) InternetHeaders(javax.mail.internet.InternetHeaders) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) DeliveryStatus(com.sun.mail.dsn.DeliveryStatus) DSNAction(org.nhindirect.common.mail.dsn.DSNStandard.DSNAction)

Aggregations

Address (javax.mail.Address)89 InternetAddress (javax.mail.internet.InternetAddress)69 MessagingException (javax.mail.MessagingException)35 MimeMessage (javax.mail.internet.MimeMessage)34 JavaMailInternetAddress (com.zimbra.common.mime.shim.JavaMailInternetAddress)21 ArrayList (java.util.ArrayList)20 Date (java.util.Date)19 MimeBodyPart (javax.mail.internet.MimeBodyPart)13 Account (com.zimbra.cs.account.Account)12 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)10 IOException (java.io.IOException)9 Locale (java.util.Locale)9 Message (javax.mail.Message)9 ItemId (com.zimbra.cs.service.util.ItemId)8 Header (javax.mail.Header)8 NHINDAddress (org.nhindirect.stagent.NHINDAddress)8 AddressException (javax.mail.internet.AddressException)7 MimeMultipart (javax.mail.internet.MimeMultipart)7 ZVCalendar (com.zimbra.common.calendar.ZCalendar.ZVCalendar)6 Invite (com.zimbra.cs.mailbox.calendar.Invite)6