How to get recipients addresses as String in JavaMail? - jakarta-mail

I have a piece of code VERY similar to this one http://java.sun.com/developer/onlineTraining/JavaMail/contents.html#JavaMailFetching
I the difference is that I need to get the "TO" addresses as a String. I can't find in the API how to get the "TO" recipients as String for each Message.
Can anyone guide me on how to do this? At least a link where someone has already done it.

Once you have a Message object (in their example it's "message[0]" since they have an array of Messages), you can do something like
List<String> toAddresses = new ArrayList<String>();
Address[] recipients = message.getRecipients(Message.RecipientType.TO);
for (Address address : recipients) {
toAddresses.add(address.toString());
}

Related

Comparing Old and new value of the record

Hope you are all doing good!!!.
I just need to fix this one and I googled the logic and when I tried I got an error and then I have copied the online code and paste that too but no use.
the logic of the below code is :Check the phone number of the account and compare old and new value of the phone number if it's not the same value then I need to update the old value in the description.
public class CheckOldAndNewValueonAccount {
public static void accNewOldValues(List<Account> accList){
for(Account acc: accList){
Account oldAcc = Trigger.oldMap.get(acc.Id);
if(acc.Phone != oldAcc.Phone){
acc.Description = 'Old Phone number this account is :'+oldAcc.Phone;
}
}
}
}
Error: Illegal assignment from SObject to Account.
Please guide me on this.
Thanks in Advance.
I believe the issue is this line:
Account oldAcc = Trigger.oldMap.get(acc.Id);
I believe the type of old map is Map<String, sObject>.
sObject is a type that is a Salesforce object (any one) but none specifically.
So you are trying to assign an sObject to a variable you are declaring as an Account type.
You can just do the following:
sObject oldAcc = Trigger.oldMap.get(acc.Id);
unless you specifically want to try and cast the sObject to an Account (concrete) type. I don't see any major benefit to doing so. Let us know if that was the problem and if this resolved it.
Edit: see this trailhead:
https://trailhead.salesforce.com/en/content/learn/modules/apex_database/apex_database_sobjects
Section: Casting Generic sObjects to Specific sObject Types
You can easily cast to Account. There is a snippet there.
Dot notation is not available on generic sObject types.
Or you can use .get('fieldname') which works on generic sObject as well.

Yii2 - mailer - send message to email rows in database

Greetings,
i need to send email to several recipients that are stored in a table named mail which has a field called email.
In my controller i created an action that Query the table mail for the emails.
Later i tried to use the implode() function separated by comma, but obviously it didn't work because of mailer policies.
It generated the wrong format -> "email1#mail.com, email2#mail.com, email3#mail.com".
Tried also a for each loop and the serialize() function without success.
The json_encode() function is close to what i need, separate an array of emails to something like -> "email1#mail.com", "email2#mail.com", "email3#mail.com".
But it appends the field name before the value and it is not accepted by mailer policies.
So far i'm stuck with the following code:
public function actionSucesso()
{
$query = new Query;
$query->select('email')
->from('mail');
$command = $query->createCommand();
$enderecos = $command->queryAll();
$enviar = json_encode($enderecos);
Yii::$app->mailer->compose()
->setFrom('atf#website.com')
->setTo($enviar)
->setSubject('Oferta de jogo no site da ATF.')
->setTextBody('Aceda em: http://atf.besaba.com/index.php?r=playschedule%2Findex2')
->send();
return $this->render('sucesso');
}
I think in order for the mailer to work and send the message the correct format needs to be: ->setTo("mail1#mail.com", "mail2#mail.com", "mail3#mail.com")
Is there a way of solving this problem?
Many thanks in advance.
To get array of email with numeric indexes call queryAll() method with $fetchMode parameter \PDO::FETCH_COLUMN, and then just pass returned array to mailer's setTo() method. Like this
$enderecos = $command->queryAll(\PDO::FETCH_COLUMN);
//$enviar = json_encode($enderecos); <- this line no needed
Yii::$app->mailer->compose()
->setFrom('atf#website.com')
->setTo($enderecos) //you pass an array of email addresses
->setSubject('Oferta de jogo no site da ATF.')
->setTextBody('Aceda em: http://atf.besaba.com/index.php?r=playschedule%2Findex2')
->send();
See queryAll() documentation and list of pdo constant including available fetch modes starting with PDO::FETCH_. Also assuming you are using yii2 default mailer, look for swiftmailer documentation about how to set recipients

Unable to translate bytes [...] at index ... from specified code page to Unicode when adding to index

I am using Newtonsoft.Json to create the JSON to update add items to an index, but I get the following error when I POST the request:
{"error":{"code":"","message":"The request is invalid.","innererror":{"message":"parameters : Unable to translate bytes [E3] at index 752 from specified code page to Unicode.\r\n","type":"","stacktrace":""}}}
I know the error occurs with some non letter characters in some of the strings in the data that I am serializing. The string data comes from SQL, so I'm guessing something is going on to do with encoding that I cannot figure out.
When I inspect the JSON string, and put it in manually construct a request with the same data in Fiddler it all works fine.
Does anyone have any idea what might be the problem, and how I can work around it?
I found my own solution after a bit more digging.
Adding "StringEscapeHandling.EscapeNonAscii" to the serialization options solves the problem:
jsonSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
StringEscapeHandling = StringEscapeHandling.EscapeNonAscii
};

multicast to a String collection

Is there an easy may to send a message to many endpoints, defined in a List<String>?
For exemple, I would like to do :
from("file://c:/inbox").to(myStringList);
Yes you will need to turn that list into an array as shown. Though doing this in pure Java is a bit ugly as the code shows:
String[] s = myStringList.toArray(new String[myStringList.size()]);
from("file://c:/inbox").to(s);

Intermitent Base64 Task Conversion Errors

I'm experiencing a really weird situation when passing on a POJO java object within the payload of a Pull Queue task using Gson. Without changing the code or the POJO being set within the payload of a task, this will randomly succeed or fail.
This is the code I'm using:
PullQueueTaskPayLoad tqp = new PullQueueTaskPayLoad("id","name");
tqp.uploadURL = taskPayLoad.uploadURL;
tqp.urls = taskPayLoad.urls;
tqp.sliceQueryParameter = taskPayLoad.sliceQueryParameter;
TaskOptions task = TaskOptions.Builder.withMethod(TaskOptions.Method.PULL);
task.payload(new Gson().toJson(tqp));
q.add(task);
Using an external queue consumer I then retrieve the POJO as follows:
Type GSON_TYPE = new TypeToken<PullQueueTaskPayLoad>() {}.getType();
byte[] b = new Base64().decodeBase64(leasedTask.getPayloadBase64().getBytes());
String payload = new String(b);
logger.info("About to convert payload: "+payload);
PullQueueTaskPayLoad taskpayload = new Gson().fromJson(payload, GSON_TYPE);
So from the debugging I did, the problem seems to be happening when I'm decoding the payload bytes. While encoding the same POJO (with different Ids) I randomly get 2 different decoded payload Strings as follows:
Correct decoding:
{"id":"1786024566","sliceQueryParameter": {"queryId":786024566,"sliceStart":-1,"sliceNumber":1,"params":{"DefaultAnnotation":{"http://www.slicepedia.org/ontology#hasNumberOfBulletPoints_SIGN":["\u003d"],"http://www.slicepedia.org/ontology#hasNumberOfBulletPoints":["0"],"http://www.slicepedia.org/ontology#hasNumberOfTokens":["80"],"http://www.slicepedia.org/ontology#hasNumberOfTokens_SIGN":["\u003e"]},"VG":{"http://www.slicepedia.org/ontology#hastense":["?"],"http://www.slicepedia.org/ontology#hasroot":["?"]}}},"uploadURL":"http://3.linguabox0412.appspot.com/_ah/upload/AMmfu6YRjxX23Ks-yh-9AZs4-3I1p6hxrFd6d4ptxSQegUkQHN7y4hNZwX6u7PufIHJbwtsHLXFZJ5P-vs90mslZEOMw0T-amN2qhEOAj_6YdwuY50FXMi8/ALBNUaYAAAAAT7Towgs4M00M5RLI8xnEOMdIxouZzuGu/","status":"IN_PROGRESS","action":"SLICE_SEARCH_AND_CREATE"}
Incorrect decoding:
{"id":"1-1968382407","sliceQueryParameter":{"queryId":-1968382407,"sliceStart":-1,"sliceNumber":1,"params":{"DefaultAnnotation":{"http://www.slicepedia.org/ontology#hasNumberOfBulletPoints_SIGN":["\u003d"],"http://www.slicepedia.org/ontology#hasNumberOfBulletPoints":["0"],"http://www.slicepedia.org/ontology#hasNumberOfTokens":["80"],"http://www.slicepedia.org/ontology#hasNumberOfTokens_SIGN":["\u003e"]},"VG":{"http://www.slicepedia.org/ontology#hastense":["?K??????˜?X?\YXK?ܙ?????H?\ܛ????Ȃ%?????'W??EU$?#?&?GG???2?Ɩ?wV&??C"?7?B?6??????W??B???gSe????'u?U'd?D??6?S??4UV?D?e7?%U?&%F%f?D?$???$&vu6?fF$????EG?v??6?6դvt?D???G??&D?fdֵ6%?甦??GD????F???$?V?CuF?$?F?F֤֧f?D??u?wt?4?C$?W?"?'7FGW2#?$???$?u$U52"?&7F???#?%4Ĕ4U?4T$4???E?5$TDR'
So the second string obviously fails when using Gson to convert it back to a POJO. But I dont' understand why this happens in only some cases and not others. For what I've seen, it seems to always happen after a ["?"] character string. I tried replacing and ? with other strings but it didn't change anything.
I think what is happening here is that the payload is webSafe-base64 encoded. In practice, this means swapping + and / and = for - and _ and .. Most base64 libraries have native support for decoding websafe base 64 strings.
Probably you are meeting one of these chars at a certain point, and that kills the decoding.
Here is some info on WebSafeBase64
Word of warning, though: the taskqueue implementation is actually sending padding equals (=) that you will have to convert manually before parsing.

Resources