base.email.encoding.QuotedPrintableEncoding Maven / Gradle / Ivy
/**
* Creative commons Attribution-NonCommercial license.
*
* http://creativecommons.org/licenses/by-nc/2.5/au/deed.en_GB
*
* NO WARRANTY IS GIVEN OR IMPLIED, USE AT YOUR OWN RISK.
*/
package base.email.encoding;
import base.text.StringHelper;
public class QuotedPrintableEncoding extends Encoding{
/**
* Break all lines greater than 80 characters long, Ensure
* all lines consistently end with CRLF, and ensure the full
* stop (period) character is escaped properly.
*/
public String encode(String message) {
if(message == null || message == "") {
return message;
}
int crlfCount = countSubstring(message, "\r\n");
int crCount = countSubstring(message, "\r");
int lfCount = countSubstring(message, "\n");
String splitBy = "\n";
if(crlfCount > crCount && crlfCount > lfCount) {
splitBy = "\r\n";
}
if(crCount > crlfCount && crCount > lfCount) {
splitBy = "\r";
}
if(lfCount > crCount && lfCount > crlfCount) {
splitBy = "\n";
}
if(crlfCount == crCount && crlfCount == lfCount) {
splitBy = "\r\n";
}
message = StringHelper.join(message.split(splitBy), "\r\n");
int lineLength = 0;
StringBuilder body = new StringBuilder();
for(int i = 0; i < message.length(); i++) {
char c = message.charAt(i);
if(c == 13 || c == 10) {
lineLength = 0;
} else {
lineLength++;
}
// Escape special or extended characters
if((c > 127 && c < 256) || c < 10 || c == '=') {
if(lineLength > 74) {
body.append("=\r\n");
lineLength = 0;
}
if(c > 15) {
body.append("=" + Integer.toHexString(c).toUpperCase());
} else {
body.append("=0" + Integer.toHexString(c).toUpperCase());
}
lineLength += 2;
// Escape full stop if it is at the start of the line
} else if(c == '.' && lineLength == 1) {
body.append(c);
body.append(c);
lineLength++;
// Otherwise just append the next character
} else {
if(lineLength > 76) {
body.append("=\r\n");
lineLength = 1;
if(c == '.') {
body.append(c);
lineLength++;
}
}
body.append(c);
}
}
if(!body.toString().endsWith("\r\n")) {
body.append("\r\n");
}
return body.toString();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy