I try to get the ID of email that I just send it through Java EWS API.
My goal is when I got that ID I would store it to Database.
This what I'm trying:
try {
String isiEmail = generateIsiEmail(nmBank, jenis, tglAw, tglAk, produk);
EmailMessage mail = new EmailMessage(service);
mail.setSubject(jdlEmail);
mail.setBody(new MessageBody(isiEmail));
//set to cc
mail.getToRecipients().add(new EmailAddress(from.replaceAll("\\s", "")));
String[] too = to.split("\\;");
for (int i = 0; i <too.length; i++) {
mail.getToRecipients().add(new EmailAddress(too[i].replaceAll("\\s", "")));
}
String[] ccc = cc.split("\\;");
for (int i = 0; i <ccc.length; i++) {
mail.getCcRecipients().add(new EmailAddress(ccc[i].replaceAll("\\s", "")));
}
mail.sendAndSaveCopy();
} catch (ServiceLocalException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Thanks for help.
I solved by my self.
this step what I'm done with.
I use ExtendedPropertyDefinition refer from this tutorial https://learn.microsoft.com/en-us/previous-versions/office/developer/exchange-server-2010/dd633654(v%3dexchg.80) , but I modified from C# into java programing language,
set ExtendedPropertyDefinition then save the uuidToStr to database
UUID uuid = UUID.randomUUID();
ExtendedPropertyDefinition epd = new ExtendedPropertyDefinition(uuid, "NamaId", MapiPropertyType.String);
String uuidToStr = uuid.toString();
String isiEmail = generateIsiEmail(nmBank, jenis, tglAw, tglAk, produk);
EmailMessage mail = new EmailMessage(service);
mail.setSubject(jdlEmail);
mail.setBody(new MessageBody(isiEmail));
//set to cc
mail.getToRecipients().add(new EmailAddress(from.replaceAll("\\s", "")));
String[] too = to.split("\\;");
for (int i = 0; i <too.length; i++){
mail.getToRecipients().add(new EmailAddress(too[i].replaceAll("\\s", "")));
}
String[] ccc = cc.split("\\;");
for (int i = 0; i <ccc.length; i++){
mail.getCcRecipients().add(new EmailAddress(ccc[i].replaceAll("\\s", "")));
}
mail.setExtendedProperty(epd, "isiId");
mail.sendAndSaveCopy();
get the email based on ExtendedPropertyDefinition uuidToStr from database
UUID uuid = UUID.fromString("cc59cdbf-aad4-4cd1-a4f0-e7819c56b884");
ExtendedPropertyDefinition epd = new ExtendedPropertyDefinition(uuid, "NamaId", MapiPropertyType.String);
ItemView view2 = new ItemView(3);
SearchFilter sf = new SearchFilter.IsEqualTo(epd,"isiId");
FindItemsResults<Item> fir = service.findItems(WellKnownFolderName.SentItems, sf, view2);
for (Item itm : fir.getItems()){
System.out.println(itm.getId());
System.out.println(itm.getSubject());
}
DONE;
You should make use of the InternetMessageId property.
Call the FindItems method to search for messages in the sent items folder. Then instantiate an EmailMessage object so you can access the InternetMessageId property:
ItemView view = new ItemView(100); // You can change this to your needs.
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.InternetMessageId);
FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.SentItems, view);
foreach (Item item in results)
{
if (item is EmailMessage)
{
EmailMessage emailMsg = item as EmailMessage;
Console.WriteLine(emailMsg.InternetMessageId);
}
}
I am using C# EWS Api, But this logic will work for you.
First you have to Save the email in Draft and then after you can get Email id.
EmailMessage emailMessage = new EmailMessage(service);
emailMessage.From = email.From;
emailMessage.Subject = email.Subject;
emailMessage.Body = new MessageBody(BodyType.HTML, email.Body);
foreach (var toAddress in email.To)
{
emailMessage.ToRecipients.Add(toAddress);
}
// Send message and save copy by default to sentItems folder
emailMessage.Save();
emailMessage.Load();
// Get Email Conversation Id.
string ConversationId = emailMessage.ConversationId.UniqueId;
string EmailMessageId;
emailMessage.SendAndSaveCopy();
// Get Email Message Id by InternetMessageId.
List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
searchFilterCollection.Add(new SearchFilter.ContainsSubstring(EmailMessageSchema.InternetMessageId, InternetMessageId));
// Create the search filter.
SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
ItemView view = new ItemView(50);
view.PropertySet = new PropertySet(BasePropertySet.IdOnly, EmailMessageSchema.InternetMessageId);
FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.SentItems, searchFilter, view);
if (results.Items.Count > 0)
{
Item item = results.Items[0];
EmailMessage message = EmailMessage.Bind(service, item.Id);
EmailMessageId = message.Id.UniqueId;
}
I believe the solution is this:
EmailMessage em = EmailMessage.bind( service, item.getId(),
new PropertySet( EmailMessageSchema.InternetMessageId) );
Explanation :
We have to bind the item to an email message, but instead of grabbing all the info, we only ask for the ID and any additional properties we want through the PropertySet parameter.
found -> Exchange Web Services get Message Message-ID
Related
I am attempting to get the items and some of the related information from a Purchase Order with SuiteTalk. I am able to get the desired Purchase Orders with TransactionSearch using the following in Scala:
val transactionSearch = new TransactionSearch
val search = new TransactionSearchBasic
...
search.setLastModifiedDate(searchLastModified) //Gets POs modified in the last 10 minutes
transactionSearch.setBasic(search)
val result = port.search(transactionSearch)
I am able to cast each result to a record as an instance of the PurchaseOrder class.
if (result.getStatus().isIsSuccess()) {
println("Transactions: " + result.getTotalRecords)
for (i <- 0 until result.getTotalRecords) {
try {
val record = result.getRecordList.getRecord.get(i).asInstanceOf[PurchaseOrder]
record.get<...>
}
catch {...}
}
}
From here I am able to use the getters to access the individual fields, except for the ItemList.
I can see in the NetSuite web interface that there are items attached to the Purchase Orders. However using getItemList on the result record is always returning a null response.
Any thoughts?
I think you have not used search preferences and that is why you are not able to fetch purchase order line items. You will have to use following search preferences in your code -
SearchPreferences prefrence = new SearchPreferences();
prefrence.bodyFieldsOnly = false;
_service.searchPreferences = prefrence;
Following is working example using above preferences -
private void SearchPurchaseOrderByID(string strPurchaseOrderId)
{
TransactionSearch tranSearch = new TransactionSearch();
TransactionSearchBasic tranSearchBasic = new TransactionSearchBasic();
RecordRef poRef = new RecordRef();
poRef.internalId = strPurchaseOrderId;
poRef.type = RecordType.purchaseOrder;
poRef.typeSpecified = true;
RecordRef[] poRefs = new RecordRef[1];
poRefs[0] = poRef;
SearchMultiSelectField poID = new SearchMultiSelectField();
poID.searchValue = poRefs;
poID.#operator = SearchMultiSelectFieldOperator.anyOf;
poID.operatorSpecified = true;
tranSearchBasic.internalId = poID;
tranSearch.basic = tranSearchBasic;
InitService();
SearchResult results = _service.search(tranSearch);
if (results.status.isSuccess && results.status.isSuccessSpecified)
{
Record[] poRecords = results.recordList;
PurchaseOrder purchaseOrder = (PurchaseOrder)poRecords[0];
PurchaseOrderItemList poItemList = purchaseOrder.itemList;
PurchaseOrderItem[] poItems = poItemList.item;
if (poItems != null && poItems.Length > 0)
{
for (var i = 0; i < poItems.Length; i++)
{
Console.WriteLine("Item Line On PO = " + poItems[i].line);
Console.WriteLine("Item Quantity = " + poItems[i].quantity);
Console.WriteLine("Item Descrition = " + poItems[i].description);
}
}
}
}
I followed this: Reading email from gmail is not working and I am able to fetch all email messages. However, when I use search parameters, I always get 0 results. This is what I tried:
Date d1 = new DateTime(date.getTime()).toLocalDate().toDate();
Date d2 = new DateTime(date.getTime()).plusDays(-30).toLocalDate().toDate();
SearchTerm olderThan = new ReceivedDateTerm(ComparisonTerm.LT, d1);
SearchTerm newerThan = new ReceivedDateTerm(ComparisonTerm.GT, d2);
SearchTerm andTerm = new AndTerm(olderThan, newerThan);
Message[] messages = emailFolder.search(andTerm);
If I change the last line to
Message[] messages = emailFolder.getMessages();
everything works fine and I get all emails. There are emails in my inbox received in the last 30 days. Is there something wrong with my search logic?
You are missing below line of code, you have to override match method and put condition there
// creates a search criterion
SearchTerm searchCondition = new SearchTerm() {
#Override
public boolean match(Message message) {
try {
if (message.getSubject().contains(keyword)) {
return true;
}
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
};
// performs search through the folder
Message[] foundMessages = folderInbox.search(searchCondition);
for (int i = 0; i < foundMessages.length; i++) {
Message message = foundMessages[i];
String subject = message.getSubject();
System.out.println("Found message #" + i + ": " + subject);
}
EDIT :-
SearchTerm andTerm = null;
andTerm = new AndTerm(andTerm, olderThan); //concat the search terms
andTerm = new AndTerm(andTerm, newerThan );
Message messages[] = folderInbox.search(andTerm); //search on the imap server
EDIT 1 :-
for (Message message : messages) {
if (message.getSentDate().after(olderThan) && message.getSentDate().before(newerThan))
{
//do whatever you want with your filtered by period message
}
}
I am trying to delete the accounts from Gigya DB, so we can reuse them to test our login function through Gigya. It seems the UID required for deletion come from login, so how am I suppose to do it in Java?
As mentioned by Ilan, firstly you'll need to include the Gigya Java SDK.
You can then look up the UID using either the Identity Access or Identity Query Tool within Gigya console and use the follow code to delete the account:
// delete user record
GSRequest deleteAccountRequest = new GSRequest(apiKey, secretKey, "accounts.deleteAccount");
//deleteAccountRequest.setAPIDomain("eu1.gigya.com"); // enable this if you're using the EU data centre
deleteAccountRequest.setUseHTTPS(true);
deleteAccountRequest.setParam("UID", uid);
GSResponse deleteAccountResponse = deleteAccountRequest.send();
if(deleteAccountResponse.getErrorCode()==0)
{
}
else
{
System.out.println("deleteAccountResponse failure: " + deleteAccountResponse.getLog());
}
Alternatively, if you want to delete users in batch, you can run a search using accounts.search and delete all the users within the results set:
int limit = 100;
String query = "select UID from accounts where ... " + limit; // add your query here i.e. email = 'someone#example.com'
String cursorId = "";
int objectsCount = limit;
GSRequest searchRequest;
ArrayList<String> uidList = new ArrayList<String>();
// send request
do
{
// check if we have an open cursor
if(cursorId.length() > 0)
{
// run next request in cursor
// set up request
searchRequest = new GSRequest(apiKey, secretKey, "accounts.search");
//searchRequest.setAPIDomain("eu1.gigya.com");
//searchRequest.setUseHTTPS(true);
// set timeout
searchRequest.setParam("timeout", 60000);
// set cursor id
searchRequest.setParam("cursorId", cursorId);
} else {
// run new request and open cursor
// set up request
searchRequest = new GSRequest(apiKey, secretKey, "accounts.search");
//searchRequest.setAPIDomain("eu1.gigya.com");
//searchRequest.setUseHTTPS(true);
// set timeout
searchRequest.setParam("timeout", 60000);
// set query
searchRequest.setParam("query", query);
// open cursor
searchRequest.setParam("openCursor", true);
}
GSResponse searchResponse = searchRequest.send();
if(searchResponse.getErrorCode()==0)
{
GSArray uids = new GSArray();
uids = searchResponse.getArray("results", uids);
for(int i=0; i<uids.length(); i++)
{
String uid;
try {
// retrieve uid and add to list of uids
uid = uids.getObject(i).getString("UID");
uidList.add(uid);
} catch (GSKeyNotFoundException e) {
}
}
cursorId = searchResponse.getString("nextCursorId", "");
objectsCount = searchResponse.getInt("objectsCount", 0);
}
else
{
System.out.println("searchRequest failure: " + searchResponse.getLog());
}
}
while (objectsCount >= limit);
for(int i=0; i<uidList.size(); i++)
{
String uid;
try {
uid = uidList.get(i);
// delete user record
GSRequest deleteAccountRequest = new GSRequest(apiKey, secretKey, "accounts.deleteAccount");
//deleteAccountRequest.setAPIDomain("eu1.gigya.com");
deleteAccountRequest.setUseHTTPS(true);
deleteAccountRequest.setParam("UID", uid);
GSResponse deleteAccountResponse = deleteAccountRequest.send();
if(deleteAccountResponse.getErrorCode()==0)
{
}
else
{
System.out.println("deleteAccountResponse failure: " + deleteAccountResponse.getLog());
}
} catch (Exception e) {
}
}
YouTubeService service = new YouTubeService("MyApp");
String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/nU9dinwMyHo";
VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl), VideoEntry.class);
String commentUrl = videoEntry.getComments().getFeedLink().getHref();
CommentFeed commentFeed = service.getFeed(new URL(commentUrl), CommentFeed.class);
for(CommentEntry comment : commentFeed.getEntries()) {
System.out.println(comment.getPlainTextContent());
Here are my codes to retrieve the youtube comments of a specific video.
I'm able to retrieve about 25 comments using this code, but how do I retrieve ALL the comments from the video?
I think it is something like:
// Get a video entry
String str = "http://gdata.youtube.com/feeds/api/videos/" + videoId;
YouTubeQuery youtubeQuery = new YouTubeQuery(new URL(str));
String videoEntryUrl = youtubeQuery.getUrl().toString();
VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl),VideoEntry.class);
// Get the comments url for this video
if (videoEntry.getComments() != null) {
String commentUrl = videoEntry.getComments().getFeedLink().getHref();
System.out.println(commentUrl);
// Get the comment feed; use a new query
YouTubeQuery youtubeQuery = new YouTubeQuery(new URL(commentUrl);
youtubeQuery.setMaxResults(50);
youtubeQuery.setStartIndex(1);
String commentUrlFeed = youtubeQuery.getUrl().toString();
CommentFeed commentFeed = service.getFeed(new URL(commentUrlFeed),CommentFeed.class);
// The response should contain an url for the next feed, if any, already with an updated start-index.
for (int i = 0; i < commentFeed.getEntries().size()
&& commentFeed.getEntries().get(i) != null; i++) {
String author=commentFeed.getEntries().get(i).getAuthors().get(0).getUri().substring(41)
String commentId=commentFeed.getEntries().get(i).getId().substring(47);
String comment=commentFeed.getEntries().get(i).getPlainTextContent();
}
}
// Loop thru next comment feed call, if more can be expected.
// Use updated url from the response or set start-index = start-index + max-results.
}
I am trying to post data in wordpress using this code but I am getting token null
In place of sXmlRpcURL I have used http://wordpress.com/ and http://sUsername.wordpress.com/ also but both the cases its generating token null.
String sXmlRpcURL= arg[0];
String sUsername = arg[1];
String sPassword = arg[2];
// Hard-coded blog_ID
int blog_ID = 1;
// XML-RPC method
String sXmlRpcMethod = "blogger.newPost";
// XML-RPC method ver 2
// sXmlRpcMethod = "metaWeblog.newPost"; // I have used this also
// We'll hard-code our blog content for now as well
String sTitle = "HI........";
String sContent = "Hello XML-RPC World!";
// Create our content struct
HashMap hmContent = new HashMap();
hmContent.put("title", sTitle);
hmContent.put("description", sContent);
// You can specify whether or not you want the blog published immediately
boolean bPublish = true;
// Try block
try {
// Create the XML-RPC client
XmlRpcClient client = new XmlRpcClient(sXmlRpcURL,true);
// Make our method call
Object token = client.invoke( sXmlRpcMethod, new Object[] { new Integer( blog_ID ), sUsername, sPassword, hmContent, new Boolean( bPublish ) } );
// The return is a String containing the postID
System.out.println("Posted : " + (String) token);
} // Catch exceptions
catch (Exception e) {
}
please help me.
I have got the solution you want to use -
http://sUsername.wordpress.com/xmlrpc.php?
for sXmlRpcURL.
Now it working well-