Java Code Examples for javax.mail.internet.MimeUtility#decodeText()

The following examples show how to use javax.mail.internet.MimeUtility#decodeText() . 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: cfMailMessageData.java    From openbd-core with GNU General Public License v3.0 7 votes vote down vote up
public static String getFilename( Part Mess ) throws MessagingException{
// Part.getFileName() doesn't take into account any encoding that may have been 
// applied to the filename so in order to obtain the correct filename we
// need to retrieve it from the Content-Disposition

String [] contentType = Mess.getHeader( "Content-Disposition" );
	if ( contentType != null && contentType.length > 0 ){
		int nameStartIndx = contentType[0].indexOf( "filename=\"" );
		if ( nameStartIndx != -1 ){
			String filename = contentType[0].substring( nameStartIndx+10, contentType[0].indexOf( '\"', nameStartIndx+10 ) );
			try {
			filename = MimeUtility.decodeText( filename );
			return filename;
		} catch (UnsupportedEncodingException e) {}
		}  		
	}

	// couldn't determine it using the above, so fall back to more reliable but 
// less correct option
	return Mess.getFileName();
}
 
Example 2
Source File: SendReceiveWithInternationalAddressTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
@Test
public void testSend() throws MessagingException, UnsupportedEncodingException {

    Session session = GreenMailUtil.getSession(ServerSetupTest.SMTP, properties);
    MimeMessage mimeMessage = new MockInternationalizedMimeMessage(session);
    mimeMessage.setSubject("subject");
    mimeMessage.setSentDate(new Date());
    mimeMessage.setFrom("múchätįldé@tìldę.oœ");
    mimeMessage.setRecipients(Message.RecipientType.TO, "用户@例子.广告");
    mimeMessage.setRecipients(Message.RecipientType.CC, "θσερεχα@μπλε.ψομ");
    mimeMessage.setRecipients(Message.RecipientType.BCC, "राममो@हन.ईन्फो");

    // The body text needs to be encoded if it contains non us-ascii characters
    mimeMessage.setText(MimeUtility.encodeText("用户@例子"));

    GreenMailUtil.sendMimeMessage(mimeMessage);

    // Decoding the body text to verify equality
    String decodedText = MimeUtility.decodeText(GreenMailUtil.getBody(greenMail.getReceivedMessages()[0]));
    assertEquals("用户@例子", decodedText);
}
 
Example 3
Source File: JavamailService.java    From lemon with Apache License 2.0 6 votes vote down vote up
public static String getFrom(MimeMessage msg) throws MessagingException,
        UnsupportedEncodingException {
    String from = "";
    Address[] froms = msg.getFrom();

    if (froms.length < 1) {
        throw new MessagingException("没有发件人!");
    }

    InternetAddress address = (InternetAddress) froms[0];
    String person = address.getPersonal();

    if (person != null) {
        person = MimeUtility.decodeText(person) + " ";
    } else {
        person = "";
    }

    from = person + "<" + address.getAddress() + ">";

    return from;
}
 
Example 4
Source File: BaseMailArchiveService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Access the from: address of the message.
 * 
 * @return The from: address of the message.
 */
public String getFromAddress()
{
	String fromAddress = ((m_fromAddress == null) ? "" : m_fromAddress);
	
	try
	{
		fromAddress = MimeUtility.decodeText(fromAddress);
	}
	catch (UnsupportedEncodingException e)
	{
		// if unable to decode RFC address, just return address as is
		log.debug(this+".getFromAddress "+e.toString());
	}
	
	return fromAddress;

}
 
Example 5
Source File: NntpUtil.java    From scava with Eclipse Public License 2.0 6 votes vote down vote up
protected static String decodeSubject(String subject) {
		if (subject.contains("=?utf-8?")) {
//			System.err.println("D: subject:\t" + subject);
			String decodedSubject = "";
        	for (String str: subject.replace("=?utf-8?", " =?utf-8?").split("\\s+"))
    			try {
    				decodedSubject += MimeUtility.decodeText(str);
    			} catch (UnsupportedEncodingException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
//    		System.err.println("D: decoded:\t" + decodedSubject);
        	return decodedSubject;
    	} else
    		return subject;
    }
 
Example 6
Source File: MimeMessageParser.java    From commons-email with Apache License 2.0 6 votes vote down vote up
/**
 * Determines the name of the data source if it is not already set.
 *
 * @param part the mail part
 * @param dataSource the data source
 * @return the name of the data source or {@code null} if no name can be determined
 * @throws MessagingException accessing the part failed
 * @throws UnsupportedEncodingException decoding the text failed
 */
protected String getDataSourceName(final Part part, final DataSource dataSource)
    throws MessagingException, UnsupportedEncodingException
{
    String result = dataSource.getName();

    if (result == null || result.length() == 0)
    {
        result = part.getFileName();
    }

    if (result != null && result.length() > 0)
    {
        result = MimeUtility.decodeText(result);
    }
    else
    {
        result = null;
    }

    return result;
}
 
Example 7
Source File: POP3Client.java    From OA with GNU General Public License v3.0 5 votes vote down vote up
public static String getChineseFrom(String res) {
	String from = res;
	try {
		if (from.startsWith("=?GB") || from.startsWith("=?gb")
				|| from.startsWith("=?UTF")) {
			from = MimeUtility.decodeText(from);
		} else {
			from = new String(from.getBytes("ISO8859_1"), "GBK");
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return from;
}
 
Example 8
Source File: MailManager.java    From Cynthia with GNU General Public License v2.0 5 votes vote down vote up
public static String getChineseFrom(String res) {
    String from = res;
    try {
        if (from.startsWith("=?GB") || from.startsWith("=?gb")
                || from.startsWith("=?UTF")) {
            from = MimeUtility.decodeText(from);
        } else {
            from = new String(from.getBytes("ISO8859_1"), "GBK");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return from;
}
 
Example 9
Source File: MessageParser.java    From translationstudio8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取消息附件中的文件.
 * @return List&lt;ResourceFileBean&gt;
 * 				文件的集合(每个 ResourceFileBean 对象中存放文件名和 InputStream 对象)
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public List<ResourceFileBean> getFiles() throws MessagingException, IOException {
	List<ResourceFileBean> resourceList = new ArrayList<ResourceFileBean>();
	Object content = message.getContent();
	Multipart mp = null;
	if (content instanceof Multipart) {
		mp = (Multipart) content;
	} else {
		return resourceList;
	}
	for (int i = 0, n = mp.getCount(); i < n; i++) {
		Part part = mp.getBodyPart(i);
		//此方法返回 Part 对象的部署类型。
		String disposition = part.getDisposition();
		//Part.ATTACHMENT 指示 Part 对象表示附件。
		//Part.INLINE 指示 Part 对象以内联方式显示。
		if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
			//part.getFileName():返回 Part 对象的文件名。
			String fileName = MimeUtility.decodeText(part.getFileName());
			//此方法为 Part 对象返回一个 InputStream 对象
			InputStream is = part.getInputStream();
			resourceList.add(new ResourceFileBean(fileName, is));
		} else if (disposition == null) {
			//附件也可以没有部署类型的方式存在
			getRelatedPart(part, resourceList);
		}
	}
	return resourceList;
}
 
Example 10
Source File: NotifyMailetsMessage.java    From james-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting static String safelyDecode(String text) {
    try {
        return MimeUtility.decodeText(text);
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("Could not decode following value {}", text, e);

        return text;
    }
}
 
Example 11
Source File: MailUtils.java    From scada with MIT License 5 votes vote down vote up
/**
 * �ı�����
 * @param encodeText ����MimeUtility.encodeText(String text)�����������ı�
 * @return �������ı�
 */ 
public static String decodeText(String encodeText) throws UnsupportedEncodingException { 
    if (encodeText == null || "".equals(encodeText)) { 
        return ""; 
    } else { 
        return MimeUtility.decodeText(encodeText); 
    } 
}
 
Example 12
Source File: StandardMultipartHttpServletRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public static String decode(String value) {
	try {
		return MimeUtility.decodeText(value);
	}
	catch (UnsupportedEncodingException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 13
Source File: GetMailMessageServiceTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
private void commonVerifiesForGetMessageContentMethod(Map<String, String> messageByType, String messageType)
        throws MessagingException, IOException {
    verify(messageMock).isMimeType(messageType);
    verify(messageMock).getContent();
    PowerMockito.verifyStatic();
    MimeUtility.decodeText(messageMockToString);
}
 
Example 14
Source File: SubethaEmailMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Method extracts file name from a message part for saving its as aa attachment. If the file name can't be extracted, it will be generated based on defaultPrefix parameter.
 * 
 * @param defaultPrefix This prefix fill be used for generating file name.
 * @param messagePart A part of message
 * @return File name.
 * @throws MessagingException
 */
private String getPartFileName(String defaultPrefix, Part messagePart) throws MessagingException
{
    String fileName = messagePart.getFileName();
    if (fileName != null)
    {
        try
        {
            fileName = MimeUtility.decodeText(fileName);
        }
        catch (UnsupportedEncodingException ex)
        {
            // Nothing to do :)
        }
    }
    else
    {
        fileName = defaultPrefix;
        if (messagePart.isMimeType(MIME_PLAIN_TEXT))
            fileName += ".txt";
        else if (messagePart.isMimeType(MIME_HTML_TEXT))
            fileName += ".html";
        else if (messagePart.isMimeType(MIME_XML_TEXT))
            fileName += ".xml";
        else if (messagePart.isMimeType(MIME_IMAGE))
            fileName += ".gif";
    }
    return fileName;
}
 
Example 15
Source File: MailUtil.java    From document-management-software with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void addAttachment(BodyPart bp, EMail email)
		throws UnsupportedEncodingException, MessagingException {
	// Skip part without a filename
	if (StringUtils.isEmpty(bp.getFileName()))
		return;

	// Skip part that is not an attachment
	String[] values = bp.getHeader("Content-Disposition");
	String disposition = "";
	if (values != null && values.length > 0)
		disposition = new ContentDisposition(values[0]).getDisposition();
	if (!disposition.contains("attachment"))
		return;

	String name = MimeUtility.decodeText(bp.getFileName());
	String fileName = FilenameUtils.getName(name);

	EMailAttachment attachment = new EMailAttachment();
	attachment.setFileName(fileName);
	attachment.setMimeType(bp.getContentType());
	attachment.setSize(bp.getSize());

	try (InputStream is = bp.getInputStream()) {
		byte[] bytes = IOUtils.toByteArray(is);
		attachment.setData(bytes);
		attachment.setSize(bytes.length);
	} catch (IOException e) {
		log.error(e.getMessage(), e);
	}
	email.addAttachment(attachment);
}
 
Example 16
Source File: MessageParser.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 获取消息附件中的文件.
 * @return List&lt;ResourceFileBean&gt;
 * 				文件的集合(每个 ResourceFileBean 对象中存放文件名和 InputStream 对象)
 * @throws MessagingException
 *             the messaging exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public List<ResourceFileBean> getFiles() throws MessagingException, IOException {
	List<ResourceFileBean> resourceList = new ArrayList<ResourceFileBean>();
	Object content = message.getContent();
	Multipart mp = null;
	if (content instanceof Multipart) {
		mp = (Multipart) content;
	} else {
		return resourceList;
	}
	for (int i = 0, n = mp.getCount(); i < n; i++) {
		Part part = mp.getBodyPart(i);
		//此方法返回 Part 对象的部署类型。
		String disposition = part.getDisposition();
		//Part.ATTACHMENT 指示 Part 对象表示附件。
		//Part.INLINE 指示 Part 对象以内联方式显示。
		if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
			//part.getFileName():返回 Part 对象的文件名。
			String fileName = MimeUtility.decodeText(part.getFileName());
			//此方法为 Part 对象返回一个 InputStream 对象
			InputStream is = part.getInputStream();
			resourceList.add(new ResourceFileBean(fileName, is));
		} else if (disposition == null) {
			//附件也可以没有部署类型的方式存在
			getRelatedPart(part, resourceList);
		}
	}
	return resourceList;
}
 
Example 17
Source File: Pop3Util.java    From anyline with Apache License 2.0 5 votes vote down vote up
/**  
 * 文本解码  
 * @param text 解码MimeUtility.encodeText(String text)方法编码后的文本  
 * @return 解码后的文本  
 * @throws UnsupportedEncodingException   UnsupportedEncodingException
 */   
public static String decode(String text) throws UnsupportedEncodingException {   
    if (text == null || "".equals(text)) {   
        return "";   
    } else {   
        return MimeUtility.decodeText(text);   
    }   
}
 
Example 18
Source File: ImapMessageTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void testEncodedFromToAddresses() throws Exception
{
    // RFC1342
    String addressString = "[email protected]";
    String personalString = "�?р�?ений Ковальчук";
    InternetAddress address = new InternetAddress(addressString, personalString, "UTF-8");
    
    // Following method returns the address with quoted personal aka <["�?р�?ений Ковальчук"] <[email protected]>>
    // NOTE! This should be coincided with RFC822MetadataExtracter. Would 'addresses' be quoted or not? 
    // String decodedAddress = address.toUnicodeString();
    // Starting from javax.mail 1.5.6 the address is folded at linear whitespace so that each line is no longer than 76 characters, if possible.
    String decodedAddress = MimeUtility.decodeText(MimeUtility.fold(6, address.toString()));
    
    // InternetAddress.toString(new Address[] {address}) - is used in the RFC822MetadataExtracter
    // So, compare with that
    assertFalse("Non ASCII characters in the address should be encoded", decodedAddress.equals(InternetAddress.toString(new Address[] {address})));
    
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    
    MimeMessageHelper messageHelper = new MimeMessageHelper(message, false, "UTF-8");
    
    messageHelper.setText("This is a sample message for ALF-5647");
    messageHelper.setSubject("This is a sample message for ALF-5647");
    messageHelper.setFrom(address);
    messageHelper.addTo(address);
    messageHelper.addCc(address);
    
    // Creating the message node in the repository
    String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate();
    FileInfo messageFile = fileFolderService.create(testImapFolderNodeRef, name, ContentModel.TYPE_CONTENT);
    // Writing a content.
    new IncomingImapMessage(messageFile, serviceRegistry, message);
    
    // Getting the transformed properties from the repository
    // cm:originator, cm:addressee, cm:addressees, imap:messageFrom, imap:messageTo, imap:messageCc
    Map<QName, Serializable> properties = nodeService.getProperties(messageFile.getNodeRef());
    
    String cmOriginator = (String) properties.get(ContentModel.PROP_ORIGINATOR);
    String cmAddressee = (String) properties.get(ContentModel.PROP_ADDRESSEE);
    @SuppressWarnings("unchecked")
    List<String> cmAddressees = (List<String>) properties.get(ContentModel.PROP_ADDRESSEES);
    String imapMessageFrom = (String) properties.get(ImapModel.PROP_MESSAGE_FROM);
    String imapMessageTo = (String) properties.get(ImapModel.PROP_MESSAGE_TO);
    String imapMessageCc = (String) properties.get(ImapModel.PROP_MESSAGE_CC);
    
    assertNotNull(cmOriginator);
    assertEquals(decodedAddress, cmOriginator);
    assertNotNull(cmAddressee);
    assertEquals(decodedAddress, cmAddressee);
    assertNotNull(cmAddressees);
    assertEquals(1, cmAddressees.size());
    assertEquals(decodedAddress, cmAddressees.get(0));
    assertNotNull(imapMessageFrom);
    assertEquals(decodedAddress, imapMessageFrom);
    assertNotNull(imapMessageTo);
    assertEquals(decodedAddress, imapMessageTo);
    assertNotNull(imapMessageCc);
    assertEquals(decodedAddress, imapMessageCc);
}
 
Example 19
Source File: JavamailService.java    From lemon with Apache License 2.0 4 votes vote down vote up
public static String getSubject(MimeMessage msg)
        throws UnsupportedEncodingException, MessagingException {
    return MimeUtility.decodeText(msg.getSubject());
}
 
Example 20
Source File: Pop3Util.java    From anyline with Apache License 2.0 2 votes vote down vote up
/**
 * 获得邮件主题  
 * @param msg 邮件内容  
 * @return 解码后的邮件主题  
 * @throws UnsupportedEncodingException UnsupportedEncodingException
 * @throws MessagingException MessagingException
 */
public static String getSubject(MimeMessage msg) throws UnsupportedEncodingException, MessagingException {   
    return MimeUtility.decodeText(msg.getSubject());   
}