Java Code Examples for javax.mail.internet.MimeMessage#getSubject()

The following examples show how to use javax.mail.internet.MimeMessage#getSubject() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Message.java    From OrigamiSMTP with MIT License 6 votes vote down vote up
/** Processes the message
 */
public void process()
{
  System.out.println("Process message");
  try
  {
    Session session = Session.getDefaultInstance(new Properties());
    InputStream inputStream = new ByteArrayInputStream(message.getBytes());
    MimeMessage mimeMessage = new MimeMessage(session, inputStream);
    if (mimeMessage.isMimeType(Constants.PLAIN_MIME))
    {
      plainMessage = mimeMessage.getContent().toString();
    }
    else if (mimeMessage.isMimeType(Constants.MULTIPART_MIME))
    {
      MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
      processMimeMultipart(mimeMultipart);
    }
    subject = mimeMessage.getSubject();
    System.out.println("Message processed");
  }
  catch (Exception ex)
  {
    ex.printStackTrace(System.err);
  }
}
 
Example 2
Source File: DSNBounce.java    From james-project with Apache License 2.0 6 votes vote down vote up
private MimeBodyPart createAttachedOriginal(Mail originalMail, TypeCode attachmentType) throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();
    MimeMessage originalMessage = originalMail.getMessage();

    if (attachmentType.equals(TypeCode.HEADS)) {
        part.setContent(new MimeMessageUtils(originalMessage).getMessageHeaders(), "text/plain");
        part.setHeader("Content-Type", "text/rfc822-headers");
    } else {
        part.setContent(originalMessage, "message/rfc822");
    }

    if ((originalMessage.getSubject() != null) && (originalMessage.getSubject().trim().length() > 0)) {
        part.setFileName(originalMessage.getSubject().trim());
    } else {
        part.setFileName("No Subject");
    }
    part.setDisposition("Attachment");
    return part;
}
 
Example 3
Source File: Pop3Util.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
 * 解析邮件 
 * @param setRead setRead
 * @param delete delete
 * @param messages   要解析的邮件列表 
 * @return return
 */ 
public List<Mail> parse( boolean setRead, boolean delete, Message... messages){ 
	List<Mail> mails = new ArrayList<Mail>(); 
	try{ 
	for (Message item:messages) { 
		Mail mail = new Mail(); 
		MimeMessage msg = (MimeMessage) item; 
		Date sendTime = msg.getSentDate(); 
		Date receiveTime = msg.getReceivedDate(); 
		String subject = msg.getSubject(); 
		boolean isSeen = isSeen(msg); 
		boolean isContainerAttachment = isContainAttachment(msg); 
		log.info("[解析邮件][subject:{}][发送时间:{}][是否已读:{}][是否包含附件:{}]",subject,DateUtil.format(sendTime),isSeen,isContainerAttachment); 
		mail.setSubject(subject); 
		mail.setSendTime(sendTime); 
		mail.setReceiveTime(receiveTime); 
		if(config.AUTO_DOWNLOAD_ATTACHMENT){ 
			if (isContainerAttachment) { 
				String dir = config.ATTACHMENT_DIR.replace("{ymd}", DateUtil.format(sendTime,"yyyyMMdd")); 
				List<File> attachments = downloadAttachment(msg, dir , sendTime, null); 
				mail.setAttachments(attachments); 
			} 
		} 
		if(!isSeen && setRead){ 
			seen(msg); 
		} 
		if(delete){ 
			delete(msg); 
		} 
		mails.add(mail); 
	} 
	}catch(Exception e){ 
		e.printStackTrace(); 
	} 
	return mails; 
}
 
Example 4
Source File: MimeMessageWrapper.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
public String getSubject() {
    MimeMessage message = getMessage();
    try {
        return message.getSubject();
    } catch (MessagingException e) {
        Debug.logError(e, module);
        return null;
    }
}
 
Example 5
Source File: BayesianAnalysis.java    From james-project with Apache License 2.0 5 votes vote down vote up
private void appendToSubject(MimeMessage message, String toAppend) {
    try {
        String subject = message.getSubject();

        if (subject == null) {
            message.setSubject(toAppend, "iso-8859-1");
        } else {
            message.setSubject(toAppend + " " + subject, "iso-8859-1");
        }
    } catch (MessagingException ex) {
        LOGGER.error("Failure to append to subject phrase: '{}'", toAppend, ex);
    }
}
 
Example 6
Source File: HeadersToHTTP.java    From james-project with Apache License 2.0 5 votes vote down vote up
private HashSet<NameValuePair> getNameValuePairs(MimeMessage message) throws UnsupportedEncodingException, MessagingException {

        // to_address
        // from
        // reply to
        // subject

        HashSet<NameValuePair> pairs = new HashSet<>();

        if (message != null) {
            if (message.getSender() != null) {
                pairs.add(new BasicNameValuePair("from", message.getSender().toString()));
            }
            if (message.getReplyTo() != null) {
                pairs.add(new BasicNameValuePair("reply_to", Arrays.toString(message.getReplyTo())));
            }
            if (message.getMessageID() != null) {
                pairs.add(new BasicNameValuePair("message_id", message.getMessageID()));
            }
            if (message.getSubject() != null) {
                pairs.add(new BasicNameValuePair("subject", message.getSubject()));
            }
            pairs.add(new BasicNameValuePair("size", Integer.toString(message.getSize())));
        }

        pairs.add(new BasicNameValuePair(parameterKey, parameterValue));

        return pairs;
    }
 
Example 7
Source File: SubjectStartsWith.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<MailAddress> match(Mail mail) throws MessagingException {
    MimeMessage mm = mail.getMessage();
    String subject = mm.getSubject();
    if (subject != null && subject.startsWith(getCondition())) {
        return mail.getRecipients();
    }
    return null;
}
 
Example 8
Source File: SubjectIs.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<MailAddress> match(Mail mail) throws javax.mail.MessagingException {
    MimeMessage mm = mail.getMessage();
    String subject = mm.getSubject();
    if (subject != null && subject.equals(getCondition())) {
        return mail.getRecipients();
    }
    return null;
}
 
Example 9
Source File: MessageToCoreToMessage.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MimeMultipart computeMultiPartResponse(Session session, MimeMessage message) throws MessagingException {
    // Extract the command and operands from the subject
    String subject = null == message.getSubject() ? "" : message.getSubject();
    if (subject.startsWith("HELP")) {
        return help();
    }
    String result = computeStringResult(session, message, subject);
    MimeMultipart multipart = new MimeMultipart();
    multipart.addBodyPart(toPart(result));
    return multipart;
}
 
Example 10
Source File: DlpDomainRules.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Stream<String> getMessageSubjects(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    if (message != null) {
        String subject = message.getSubject();
        if (subject != null) {
            return Stream.of(subject);
        }
    }
    return Stream.of();
}
 
Example 11
Source File: ListDestination.java    From mireka with Apache License 2.0 5 votes vote down vote up
private void setSubject(MimeMessage outgoingMessage)
        throws MessagingException {
    if (subjectPrefix == null)
        return;
    String subj = outgoingMessage.getSubject();
    if (subj == null) {
        subj = "";
    }
    subj = normalizeSubject(subj, subjectPrefix);
    outgoingMessage.setSubject(subj, "UTF-8");
}
 
Example 12
Source File: NotifyMailetsMessage.java    From james-project with Apache License 2.0 4 votes vote down vote up
public String generateMessage(String parameterMessage, Mail originalMail) throws MessagingException {
    MimeMessage message = originalMail.getMessage();
    StringBuilder builder = new StringBuilder();

    builder.append(parameterMessage).append(LINE_BREAK);
    if (originalMail.getErrorMessage() != null) {
        builder.append(LINE_BREAK)
            .append("Error message below:")
            .append(LINE_BREAK)
            .append(originalMail.getErrorMessage())
            .append(LINE_BREAK);
    }
    builder.append(LINE_BREAK)
        .append("Message details:")
        .append(LINE_BREAK);

    if (message.getSubject() != null) {
        builder.append("  Subject: ")
            .append(safelyDecode(message.getSubject()))
            .append(LINE_BREAK);
    }
    if (message.getSentDate() != null) {
        builder.append("  Sent date: " + message.getSentDate())
            .append(LINE_BREAK);
    }
    builder.append("  MAIL FROM: " + originalMail.getMaybeSender().asString())
        .append(LINE_BREAK);

    boolean firstRecipient = true;
    for (MailAddress recipient : originalMail.getRecipients()) {
        if (firstRecipient) {
            builder.append("  RCPT TO: " + recipient)
                .append(LINE_BREAK);
            firstRecipient = false;
        } else {
            builder.append("           " + recipient)
                .append(LINE_BREAK);
        }
    }

    appendAddresses(builder, "From", message.getHeader(RFC2822Headers.FROM));
    appendAddresses(builder, "To", message.getHeader(RFC2822Headers.TO));
    appendAddresses(builder, "CC", message.getHeader(RFC2822Headers.CC));

    getMessageSizeEstimation(originalMail).ifPresent(size ->
        builder
            .append("  Size: ")
            .append(SizeUtils.humanReadableSize(size))
            .append(LINE_BREAK));

    if (message.getLineCount() >= 0) {
        builder.append("  Number of lines: " + message.getLineCount())
            .append(LINE_BREAK);
    }

    return builder.toString();
}
 
Example 13
Source File: WhiteListManager.java    From james-project with Apache License 2.0 4 votes vote down vote up
private void sendReplyFromPostmaster(Mail mail, String stringContent) {
    try {
        MailAddress notifier = getMailetContext().getPostmaster();

        MailAddress senderMailAddress = mail.getMaybeSender().get();

        MimeMessage message = mail.getMessage();
        // Create the reply message
        MimeMessage reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));

        // Create the list of recipients in the Address[] format
        InternetAddress[] rcptAddr = new InternetAddress[1];
        rcptAddr[0] = senderMailAddress.toInternetAddress();
        reply.setRecipients(Message.RecipientType.TO, rcptAddr);

        // Set the sender...
        reply.setFrom(notifier.toInternetAddress());

        // Create the message body
        MimeMultipart multipart = new MimeMultipart();
        // Add message as the first mime body part
        MimeBodyPart part = new MimeBodyPart();
        part.setContent(stringContent, "text/plain");
        part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
        multipart.addBodyPart(part);

        reply.setContent(multipart);
        reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());

        // Create the list of recipients in our MailAddress format
        Set<MailAddress> recipients = new HashSet<>();
        recipients.add(senderMailAddress);

        // Set additional headers
        if (reply.getHeader(RFC2822Headers.DATE) == null) {
            reply.setHeader(RFC2822Headers.DATE, DateFormats.RFC822_DATE_FORMAT.format(LocalDateTime.now()));
        }
        String subject = message.getSubject();
        if (subject == null) {
            subject = "";
        }
        if (subject.indexOf("Re:") == 0) {
            reply.setSubject(subject);
        } else {
            reply.setSubject("Re:" + subject);
        }
        reply.setHeader(RFC2822Headers.IN_REPLY_TO, message.getMessageID());

        // Send it off...
        getMailetContext().sendMail(notifier, recipients, reply);
    } catch (Exception e) {
        LOGGER.error("Exception found sending reply", e);
    }
}
 
Example 14
Source File: EmailAccount.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
private boolean isStudentCourseJoinRegistrationEmail(MimeMessage message, String courseName, String courseId)
        throws MessagingException {
    String subject = message.getSubject();
    return subject != null && subject.equals(String.format(EmailType.STUDENT_COURSE_JOIN.getSubject(),
            courseName, courseId));
}
 
Example 15
Source File: MimeProperties.java    From appengine-tck with Apache License 2.0 4 votes vote down vote up
private void initWithMimeMessage(MimeMessage mime) {
    try {
        if (mime.getSubject() != null) {
            subject = mime.getSubject();
        }

        if (mime.getFrom() != null) {
            from = mime.getFrom()[0].toString();
        }

        Address[] addresses;
        addresses = mime.getRecipients(Message.RecipientType.TO);
        if (addresses != null) {
            to = addresses[0].toString();
        }

        addresses = mime.getRecipients(Message.RecipientType.CC);
        if (addresses != null) {
            cc = addresses[0].toString();
        }

        addresses = mime.getRecipients(Message.RecipientType.BCC);
        if (addresses != null) {
            bcc = addresses[0].toString();
        }

        addresses = mime.getReplyTo();
        if (addresses != null) {
            replyTo = addresses[0].toString();
        }

        if (mime.getContent() instanceof String) {
            body = mime.getContent().toString().trim();
            log.info("ContentTypeString: " + mime.getContentType());
            log.info("ContentString: " + mime.getContent().toString().trim());
        }

        if (mime.getContent() instanceof Multipart) {
            Multipart multipart = (Multipart) mime.getContent();
            for (int i = 0; i < multipart.getCount(); i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                String content = getContentAsString(bodyPart);
                log.info("ContentTypeMultiPart: " + bodyPart.getContentType());
                log.info("Content: " + content);
                multiPartsList.add(content);
            }
        }

    } catch (MessagingException | IOException me) {
        throw new IllegalStateException(me);
    }
}