Special symbols in subject of emails - jakarta-mail

We are currently working on a defect to allow special symbols also to be seen in email subject. The email is text/html mime type.
Currently, if the subject should have a heart symbol it is shown as "&heart" but in the email body a "heart" symbol is shown.
Can someone help us with the solution to have special symbols also part of subject?
Here is the code snippet.
public boolean send(String to, String from, String subject, String templatePath, Map map) {
// create a mime message using the mail sender implementation
MimeMessage mimeMessage = mailSender.createMimeMessage();
// create the message using the specified template
MimeMessageHelper helper;
try
{
helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setTo(to);
helper.setSubject(subject);
helper.setFrom(from);
String text = VelocityEngineUtils.mergeTemplateIntoString(engine, templatePath, map);
helper.setText(text, true);
send(mimeMessage);
log.debug("in send at start" + this.getClass().getName()
+ ":SUCCESS: Sendig mail to" + to + " from " + from + " subject "
+ subject);
} catch (MessagingException e)
{
throw new MailPreparationException("unable to create the mime message helper", e);
} catch (Exception e)
{
log.debug("in send at start" + this.getClass().getName() + ":Failed sending mail"
+ to + " from " + from + " subject " + subject);
// throw new
// MailPreparationException("unable to create the mime message helper",
// e);
}
return false;
}
public boolean send(MimeMessage mimeMessage) throws Exception {
try
{
Multipart multipart = new MimeMultipart();
BodyPart bodyPart = new MimeBodyPart();
multipart.addBodyPart(bodyPart);
bodyPart.setContent(mimeMessage.getContent(), "text/html");
mimeMessage.setContent(multipart);
mailSender.send(mimeMessage);
} catch (Exception e)
{
log.error("in send at start" + this.getClass().getName() + ":Failed sending mail"
+ e.getMessage());
// e.printStackTrace();
throw e;
// return false;
}
return true;
}

public static String HTMLDecode(String encodedHTML) {
return encodedHTML.replaceAll("¡", "\u00A1")
.replaceAll("¢", "\u00A2")
.replaceAll("£", "\u00A3")
.replaceAll("¤", "\u00A4")
.replaceAll("¥", "\u00A5")
.replaceAll("¦", "\u00A6")
.replaceAll("§", "\u00A7")
.replaceAll("¨", "\u00A8")
........

You can send as Unicode / UTF-8.

Related

How to set a Camel exchangeProperty from a unit test

I have a bunch of unit tests that run camel routes with code like
// setup code here...
String route = "direct:someroute";
try (CamelContext context = new DefaultCamelContext()) {
Object response = runCamelRoute(context, route, ci);
checkResponse(route, response);
}
but this route expects an exchange property to be set before it gets here - how can I set it? CamelContext has a whole lot of methods but I can't seem to find something like:
CamelRoute cr = context.getRoute(route);
cr.getExchange().setProperty("propertyName", "propetyValue");
Here is my camel run method for unit testing, with a bit of extra code for setting up an Oracle connection, etc.
protected Object runCamelRoute(CamelContext context, String route, Object message) throws Exception {
context.addRoutes(new MyRouteBuilder() {
});
setupRegistry(context);
context.start();
FluentProducerTemplate template = context.createFluentProducerTemplate();
template.withBody(message)
.withHeader("hello", "goodbye")
.withProcessor(e -> e.setProperty("propertyName", "propertyValue")) // fail use header instead
.to(route);
try {
Future<Object> future = template.asyncRequest();
return future.get();
}
catch(Exception ex) {
System.out.println(route + " " + ex.getClass().getCanonicleName() + " " + ex.getMessage());
throw ex;
}
finally {
template.stop();
context.stop();
}
}
private void setupRegistry(CamelContext context) {
DataSource ds = DataSourceHelper.createConnectionPoolDev();
context.getRegistry().bind("dataSource", ds);
context.getRegistry().bind("Transformer", new Transformer());
}
public static OracleDataSource createConnectionPoolDev() {
try {
OracleDataSource ds = new OracleDataSource();
ds.setConnectionCacheName("oraCache");
ds.setURL("jdbc:oracle:thin:#//cluster:1521/server.domain.ca");
ds.setUser("user");
ds.setPassword("pass");
return ds;
}
catch (Exception ex) {
logger.error("Failed to create connection to the database " + ex.getMessage());
}
return null;
}
Something like this may be ?
context.createFluentProducerTemplate()
.withBody(...)
.withHeader(..., ...)
.withProcessor( e -> e.setProperty(propertyName, propertyValue) )
.to("direct:someroute")
.send();

How should I send an mail using JavaMail and AWS

Hello everyone i am trying to send an email using JavaMail and Amazon SES, this is the code I have written,
static Properties props = new Properties();
static {
props.setProperty("mail.transport.protocol", "aws");
props.setProperty("mail.aws.user", "userName");
props.setProperty("mail.aws.password", "secretKey");
}
void doThis() throws AddressException, MessagingException {
Session session = Session.getDefaultInstance(props);
Message mimeMessage = new MimeMessage(session);
mimeMessage.setFrom(new InternetAddress("support#xyz.com"));
mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse("kaustubh#xyz.com"));
mimeMessage.setSubject("Subject");
mimeMessage.setContent("Message contenet", "text/html");
Transport t = new AWSJavaMailTransport(session, null);
t.connect();
t.sendMessage(mimeMessage, null);
t.close();
}
but i am getting an exception saying,
Exception in thread "main" javax.mail.SendFailedException: Unable to send email;
nested exception is:
com.amazonaws.services.simpleemail.model.MessageRejectedException: Email address is not verified. The following identities failed the check in region US-EAST-1
And I am not getting any solution for this, any suggestions from the stackOverflow family would be a great help.
Here is V2 SES code that sends email...
public class SendMessage {
// This value is set as an input parameter
private static String SENDER = "";
// This value is set as an input parameter
private static String RECIPIENT = "";
// This value is set as an input parameter
private static String SUBJECT = "";
// The email body for recipients with non-HTML email clients
private static String BODY_TEXT = "Hello,\r\n" + "Here is a list of customers to contact.";
// The HTML body of the email
private static String BODY_HTML = "<html>" + "<head></head>" + "<body>" + "<h1>Hello!</h1>"
+ "<p>Here is a list of customers to contact.</p>" + "</body>" + "</html>";
public static void main(String[] args) throws IOException {
if (args.length < 3) {
System.out.println("Please specify a sender email address, a recipient email address, and a subject line");
System.exit(1);
}
// snippet-start:[ses.java2.sendmessage.main]
SENDER = args[0];
RECIPIENT = args[1];
SUBJECT = args[2];
try {
send();
} catch (IOException | MessagingException e) {
e.getStackTrace();
}
}
public static void send() throws AddressException, MessagingException, IOException {
Session session = Session.getDefaultInstance(new Properties());
// Create a new MimeMessage object
MimeMessage message = new MimeMessage(session);
// Add subject, from and to lines
message.setSubject(SUBJECT, "UTF-8");
message.setFrom(new InternetAddress(SENDER));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(RECIPIENT));
// Create a multipart/alternative child container
MimeMultipart msgBody = new MimeMultipart("alternative");
// Create a wrapper for the HTML and text parts
MimeBodyPart wrap = new MimeBodyPart();
// Define the text part
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(BODY_TEXT, "text/plain; charset=UTF-8");
// Define the HTML part
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(BODY_HTML, "text/html; charset=UTF-8");
// Add the text and HTML parts to the child container
msgBody.addBodyPart(textPart);
msgBody.addBodyPart(htmlPart);
// Add the child container to the wrapper object
wrap.setContent(msgBody);
// Create a multipart/mixed parent container
MimeMultipart msg = new MimeMultipart("mixed");
// Add the parent container to the message
message.setContent(msg);
// Add the multipart/alternative part to the message
msg.addBodyPart(wrap);
try {
System.out.println("Attempting to send an email through Amazon SES " + "using the AWS SDK for Java...");
Region region = Region.US_WEST_2;
SesClient client = SesClient.builder().region(region).build();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
message.writeTo(outputStream);
ByteBuffer buf = ByteBuffer.wrap(outputStream.toByteArray());
byte[] arr = new byte[buf.remaining()];
buf.get(arr);
SdkBytes data = SdkBytes.fromByteArray(arr);
RawMessage rawMessage = RawMessage.builder()
.data(data)
.build();
SendRawEmailRequest rawEmailRequest = SendRawEmailRequest.builder()
.rawMessage(rawMessage)
.build();
client.sendRawEmail(rawEmailRequest);
} catch (SdkException e) {
e.getStackTrace();
}
// snippet-end:[ses.java2.sendmessage.main]
}
}
// snippet-end:[ses.java2.sendmessage.complete]
Exception in thread "main" javax.mail.SendFailedException: Unable to send email; nested exception is: com.amazonaws.services.simpleemail.model.MessageRejectedException: Email address is not verified. The following identities failed the check in region US-EAST-1
Amazon is telling you that you must verify the email address you're sending from or to. If the email address from and to are not verified the send email fails.

Send JSon from Server to Client in GCM

I am Using GCM (Google Cloud Messaging).In that what i want i want to send J Son from the server side .On Client side I want to receive that for simple message i have done but i am stucked how could i pass J Son from the server side to the client side.
Please help me to resolve this.
This is my Server side code
public class GCMBroadcast extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String SENDER_ID = "";
private static final String ANDROID_DEVICE = "";
private List<String> androidTargets = new ArrayList<String>();
public GCMBroadcast() {
super();
androidTargets.add(ANDROID_DEVICE);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String collapseKey = "";
String userMessage = "";
try {
userMessage = request.getParameter("Message");
collapseKey = request.getParameter("CollapseKey");
} catch (Exception e) {
e.printStackTrace();
return;
}
Sender sender = new Sender(SENDER_ID);
Message message = new Message.Builder()
.collapseKey(collapseKey)
.addData("message", userMessage)
.build();
try {
MulticastResult result = sender.send(message, androidTargets, 1);
System.out.println("Response: " + result.getResults().toString());
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
System.out.println("response " +canonicalRegId );
}
} else {
int error = result.getFailure();
System.out.println("Broadcast failure: " + error);
}
} catch (Exception e) {
e.printStackTrace();
}
request.setAttribute("CollapseKey", collapseKey);
request.setAttribute("Message", userMessage);
request.getRequestDispatcher("XX.jsp").forward(request, response);
}
}
Your payload (added to the Message by calls to addData) can only be name/value pairs. If you want to send a JSON, you can put a JSON string in the value of such name/value pair. Then you'll have to parse that JSON yourself in the client side.
For example :
.addData("message","{\"some_json_key\":\"some_json_value\"}")

Sending SMS from BlackBerry Simulator

I'm developing a BlackBerry Application where I should send Text SMS from BlackBerry Device.
As I'm new to Blackberry, started few days back I'm unable to proceed.
Can anyone Help with providing code snippets for send SMS from BlackBerry Device or Simulator?
Thanks in Advance.
Suresh.
public static void sendSMS(final String no, final String msg) {
// try {
new Thread() {
public void run() {
boolean smsSuccess = false;
if (RadioInfo.getNetworkType() == RadioInfo.NETWORK_CDMA) {
DatagramConnection dc = null;
try {
dc = (DatagramConnection) Connector.open("sms://" + no);
byte[] data = msg.getBytes();
Datagram dg = dc.newDatagram(dc.getMaximumLength());
dg.setData(data, 0, data.length);
dc.send(dg);
// / send successfully
smsSuccess = true;
} catch (Exception e) {
System.out.println("Exception 1 : " + e.toString());
e.printStackTrace();
smsSuccess = false;
} finally {
try {
dc.close();
dc = null;
} catch (IOException e) {
System.out.println("Exception 2 : " + e.toString());
e.printStackTrace();
}
}
} else {
MessageConnection conn = null;
try {
conn = (MessageConnection) Connector
.open("sms://" + no);
TextMessage tmsg = (TextMessage) conn
.newMessage(MessageConnection.TEXT_MESSAGE);
tmsg.setAddress("sms://" + no);
tmsg.setPayloadText(msg);
conn.send(tmsg);
smsSuccess = true;
} catch (Exception e) {
smsSuccess = false;
System.out.println("Exception 3 : " + e.toString());
e.printStackTrace();
} finally {
try {
conn.close();
conn = null;
} catch (IOException e) {
System.out.println("Exception 4 : " + e.toString());
e.printStackTrace();
}
}
}
if(smsSuccess)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("success");
}
});
}else
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Dialog.alert("failure");
}
});
}
}
}.start();
}
Check out the the above code function .... to send SMS from Blackberry
You haven't specified what language you are developing in, but if you are developing in java and, if you are using Eclipse for your development with the Blackberry Java plugins, you will find a wealth of sample applications in the plugins folder hierarchy. The actual location will depend on where you have installed Eclipse, but e.g. on my machine they are at: C:\Program Files\Eclipse\eclipse 3.6.2 BlackBerry\plugins\net.rim.ejde.componentpack7.0.0_7.0.0.33\components\samples\com\rim\samples\device for the OS7 samples. Similar samples will exist for the different OS plugins you have installed.
There is a long standing sample in most OS sample sets called smsdemo which should give you all the code you need. Even if you are not developing in java, this sample should give you an indication of the path you need to take to fulfil your requirement.

How to print from servlet to webpage?

Hi I am trying to print the list from servlet to web screen (jsp)
I am using log and it's not working.
Is there anyway to do or am I using this wrong?
private static final Logger log = Logger.getLogger(TodoServiceServlet.class.getName());
.....
Todo tmp = pm.getObjectById(Todo.class, user.getEmail());
System.out.println("user email: " + user.getEmail());
if(tmp==null){
log.info("You have not stored any todo lists yet");
}else{
System.out.println("user email is there?: " + tmp.getEmail());
System.out.println("start printing");
ArrayList<String> todolists = tmp.getList();
if(todolists==null)
System.out.println("Arraylist null");
if(!todolists.isEmpty()){
for(String t : todolists){
System.out.println("In the list: " + t);
log.info("You need to do: " + t);
}
}else{
log.info("You have nothing to do chil out!");
}
System.out would print to "standard out" on the web server (usually the console) not to the screen. What you have to do is instead write to the HttpServletResponse
so something like this:
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
try {
resp.getWriter().println("user email is there?: " + tmp.getEmail());
} catch (IOException e) {
// handle your error here
}
}

Resources