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

The following examples show how to use javax.mail.internet.MimeUtility#encodeText() . 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: MailServiceImpl.java    From OneBlog with GNU General Public License v3.0 6 votes vote down vote up
private void sendMessage(MailDetail detail, String from) {
    log.info("Start to send html email for [{}({})]", detail.getToUsername(), detail.getToMailAddress());
    if (StringUtils.isEmpty(detail.getToMailAddress())) {
        log.warn("邮件接收者为空!");
        return;
    }
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        InternetAddress fromAddress = new InternetAddress(MimeUtility.encodeText("网站管理员") + "<" + from + ">");
        helper.setFrom(fromAddress);
        InternetAddress toAddress = new InternetAddress(MimeUtility.encodeText(detail.getToMailAddress()) + "<" + detail.getToMailAddress() + ">");
        helper.setTo(toAddress);
        helper.setSubject(detail.getSubject());
        helper.setText(detail.getContent(), detail.isHtml());
        if (detail.getCc() != null && detail.getCc().length > 0) {
            helper.setCc(detail.getCc());
        }
        javaMailSender.send(message);
    } catch (MessagingException | UnsupportedEncodingException e) {
        log.error("Failed to send E-mail. e [{}]", e.getMessage());
    }
}
 
Example 2
Source File: ContentModelMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This method builds {@link MimeMessage} based on {@link ContentModel}
 * 
 * @throws MessagingException
 */
private void buildContentModelMessage() throws MessagingException
{
    Map<QName, Serializable> properties = messageFileInfo.getProperties();
    String prop = null;
    setSentDate(messageFileInfo.getModifiedDate());
    // Add FROM address
    Address[] addressList = buildSenderFromAddress();
    addFrom(addressList);
    // Add TO address
    addressList = buildRecipientToAddress();
    addRecipients(RecipientType.TO, addressList);
    prop = (String) properties.get(ContentModel.PROP_TITLE);
    try
    {
        prop = (prop == null || prop.equals("")) ? messageFileInfo.getName() : prop;
        prop = MimeUtility.encodeText(prop, AlfrescoImapConst.UTF_8, null);
    }
    catch (UnsupportedEncodingException e)
    {
        // ignore
    }
    setSubject(prop);
    setContent(buildContentModelMultipart());
}
 
Example 3
Source File: SendReceiveWithInternationalAddressTest.java    From greenmail with Apache License 2.0 6 votes vote down vote up
private void setAddressHeader(String name, InternetAddress[] addresses)
        throws MessagingException {

    try {

        // Encoding the email addresses so they are correctly sent to the mail server.
        for (int i = 0; i < addresses.length; i++) {
            String addStr = MimeUtility.encodeText(addresses[i].getAddress());
            InternetAddress ia = new InternetAddress();
            ia.setAddress(addStr);
            addresses[i] = ia;
        }

        String s = InternetAddress.toString(addresses, name.length() + 2);
        setHeader(name, s);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: FormHttpMessageConverter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public static String encode(String value, String charset) {
	try {
		return MimeUtility.encodeText(value, charset, null);
	}
	catch (UnsupportedEncodingException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 5
Source File: MailWriterMeta.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private String encode (String s) {
	try {
		return MimeUtility.encodeText (s, "UTF-8", "Q");
	} catch (UnsupportedEncodingException e) {
		return s;
	}
}
 
Example 6
Source File: FormHttpMessageConverter.java    From java-technology-stack with MIT License 5 votes vote down vote up
public static String encode(String value, String charset) {
	try {
		return MimeUtility.encodeText(value, charset, null);
	}
	catch (UnsupportedEncodingException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 7
Source File: FormHttpMessageConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static String encode(String value, String charset) {
	try {
		return MimeUtility.encodeText(value, charset, null);
	}
	catch (UnsupportedEncodingException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 8
Source File: FileUtil.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Encode a filename in such a way that the UTF-8 characters won't be munged during the download by a browser. Need
    * the request to work out the user's browser type
    *
    * @return encoded filename
    * @throws UnsupportedEncodingException
    */
   public static String encodeFilenameForDownload(HttpServletRequest request, String unEncodedFilename)
    throws UnsupportedEncodingException {

// Different browsers handle stream downloads differently LDEV-1243
String agent = request.getHeader("USER-AGENT");
String filename = null;

if ((null != agent) && (-1 != agent.indexOf("MSIE"))) {
    // if MSIE then urlencode it
    filename = URLEncoder.encode(unEncodedFilename, FileUtil.ENCODING_UTF_8);

} else if ((null != agent) && (-1 != agent.indexOf("Mozilla"))) {
    // if Mozilla then base64 url_safe encoding
    filename = MimeUtility.encodeText(unEncodedFilename, FileUtil.ENCODING_UTF_8, "B");

} else {
    // any others use same filename.
    filename = unEncodedFilename;

}

// wrap filename in quotes as if it contains comma character Chrome can throw a multiple headers error
filename = "\"" + filename + "\"";

return filename;
   }
 
Example 9
Source File: UTF8toASCII.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
public static String encodeTextQP(String original) {
	String encoded = null;
	try {
		encoded = MimeUtility.encodeText(original, "UTF-8", "Q");
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
	}
	return encoded;
}
 
Example 10
Source File: FormHttpMessageConverter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public static String encode(String value, String charset) {
	try {
		return MimeUtility.encodeText(value, charset, null);
	}
	catch (UnsupportedEncodingException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 11
Source File: FileUtils.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Encode specified value as RFC 2047
 * @param name
 * @return
 * @throws Exception
 */
public static String encode(String name) {
    try {
        return MimeUtility.encodeText(name, "UTF-8", null);
    } catch (UnsupportedEncodingException e) {
        throw Throwables.asRuntime(e);
    }
}
 
Example 12
Source File: FormHttpMessageConverter.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static String encode(String value, String charset) {
	try {
		return MimeUtility.encodeText(value, charset, null);
	}
	catch (UnsupportedEncodingException ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 13
Source File: cfMAIL.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private void addAttachments( Enumeration<fileAttachment> _attach, Multipart _parent, boolean _isInline ) throws MessagingException{
	while ( _attach.hasMoreElements() ){
		fileAttachment nextFile = _attach.nextElement();
		FileDataSource fds 			= new FileDataSource( nextFile.getFilepath() );
		String mimeType = nextFile.getMimetype();
		if (mimeType == null){
			// if mime type not supplied then auto detect
			mimeType = FileTypeMap.getDefaultFileTypeMap().getContentType(nextFile.getFilepath());
     }else{
			// since mime type is not null then it the mime type has been set manually therefore
			// we need to ensure that any call to the underlying FileDataSource.getFileTypeMap()
			// returns a FileTypeMap that will map to this type
			fds.setFileTypeMap(new CustomFileTypeMap(mimeType));
		}
		
		String filename = cleanName(fds.getName());
		try {
			// encode the filename to ensure that it contains US-ASCII characters only
			filename = MimeUtility.encodeText( filename, "utf-8", "b" );
		} catch (UnsupportedEncodingException e5) {
			// shouldn't occur
		}
	  MimeBodyPart mimeAttach	= new MimeBodyPart();
	  mimeAttach.setDataHandler( new DataHandler(fds) );
		mimeAttach.setFileName( filename );

		ContentType ct = new ContentType(mimeType);
		ct.setParameter("name", filename );
		
		mimeAttach.setHeader("Content-Type", ct.toString() );

		if ( _isInline ){
       mimeAttach.setDisposition( "inline" );
       mimeAttach.addHeader( "Content-id", "<" + nextFile.getContentid() + ">" );
		}
     
		_parent.addBodyPart(mimeAttach);
	}
}
 
Example 14
Source File: SendMail.java    From OA with GNU General Public License v3.0 5 votes vote down vote up
public String translateChinese(String strText) {
	try {
		// MimeUtility.encodeText(String text, String charset, String
		// encoding) throws java.io.UnsupportedEncodingException
		// text 头值 . charset 字符集。如果此参数为 null,则使用平台的默认字符集。
		// encoding 要使用的编码。当前支持的值为 "B" 和 "Q"。如果此参数为 null,则在大部分字符使用 ASCII
		// 字符集编码时使用 "Q" 编码;其他情况使用 "B" 编码。
		strText = MimeUtility.encodeText(new String(strText.getBytes(),
				"gbk"), "gbk", "B");
	} catch (Exception e) {
		e.printStackTrace();
	}
	return strText;
}
 
Example 15
Source File: WebUtils.java    From document-management-system with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Prepare to send the file.
 */
public static void prepareSendFile(HttpServletRequest request, HttpServletResponse response,
                                   String fileName, String mimeType, boolean inline) throws UnsupportedEncodingException {
	String userAgent = WebUtils.getHeader(request, "user-agent").toLowerCase();

	// Disable browser cache
	response.setHeader("Expires", "Sat, 6 May 1971 12:00:00 GMT");
	response.setHeader("Cache-Control", "must-revalidate");
	response.addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	response.addHeader("Cache-Control", "post-check=0, pre-check=0");
	response.setHeader("Pragma", "no-cache");

	// Set MIME type
	response.setContentType(mimeType);

	if (userAgent.contains("msie") || userAgent.contains("trident")) {
		log.debug("Agent: Explorer ({})", request.getServerPort());
		fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");

		if (request.getServerPort() == 443) {
			log.debug("HTTPS detected! Apply IE workaround...");
			response.setHeader("Cache-Control", "max-age=1");
			response.setHeader("Pragma", "public");
		}
	} else if (userAgent.contains("iphone") || userAgent.contains("ipad")) {
		log.debug("Agent: iPhone - iPad");
		// Do nothing
	} else if (userAgent.contains("android")) {
		log.debug("Agent: Android");
		fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", " ");
	} else if (userAgent.contains("mozilla")) {
		log.debug("Agent: Mozilla");
		fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
	} else {
		log.debug("Agent: Unknown");
	}

	if (inline) {
		response.setHeader("Content-disposition", "inline; filename=\"" + fileName + "\"");
	} else {
		response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");
	}
}
 
Example 16
Source File: FileCommandExecutor.java    From elfinder-2.x-servlet with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private String getAttachementFileName(String fileName, String userAgent)
		throws UnsupportedEncodingException
{
	if (userAgent != null)
	{
		userAgent = userAgent.toLowerCase();

		if (userAgent.indexOf("msie") != -1)
		{
			return "filename=\"" + URLEncoder.encode(fileName, "UTF8")
					+ "\"";
		}

		// Opera浏览器只能采用filename*
		if (userAgent.indexOf("opera") != -1)
		{
			return "filename*=UTF-8''"
					+ URLEncoder.encode(fileName, "UTF8");
		}
		// Safari浏览器,只能采用ISO编码的中文输出
		if (userAgent.indexOf("safari") != -1)
		{
			return "filename=\""
					+ new String(fileName.getBytes("UTF-8"), "ISO8859-1")
					+ "\"";
		}
		// Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出
		if (userAgent.indexOf("applewebkit") != -1)
		{
			return "filename=\""
					+ MimeUtility.encodeText(fileName, "UTF8", "B") + "\"";
		}
		// FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出
		if (userAgent.indexOf("mozilla") != -1)
		{
			return "filename*=UTF-8''"
					+ URLEncoder.encode(fileName, "UTF8");
		}
	}

	return "filename=\"" + URLEncoder.encode(fileName, "UTF8") + "\"";
}