Change "from" field in LotusNotes - java

I'm sending an email using LotusNotes API, what I need to do is to change the "from" field value, please find the code below:
public void sendEmail(String recipient, String subject, String bodyText,String from) throws NotesException {
Session dominoSession = NotesFactory.createSession(dominoServer, dominoUsername, dominoPassword);
Database dominoDb = dominoSession.getDatabase(dominoServer, dominoMailbox);
Document memo = dominoDb.createDocument();
memo.appendItemValue("Form", "Memo");
memo.appendItemValue("Importance", "1");
memo.appendItemValue("Subject", subject);
memo.appendItemValue("Body", bodyText);
memo.send(false, recipient);
dominoDb.recycle();
dominoSession.recycle();
}

You can't change it. The server always puts the current username into the 'From' field. You can have a different sender in the 'Principal', but the mail will still show who actually sent it.
But there is a workaround: instead of sending the mail put the mail document directly into mail.box on the server. Then you can use the 'From' field content of your choice.

I edited Michele's answer to clarify things a little bit. If you are a beginner, I would not suggest that you use the (undocumented) mail.box approach... You need to know what you are doing there.
I created a mail notification class in Lotusscript a while back, you can take a look at it if you like. Perhaps it will help you.
http://blog.texasswede.com/lotusscript-mail-notification-class/
But again, if you don't know what you are doing, be very very careful... :-)

This is how I solved it, to set the "from" property:
public void sendEmail(final String recipient, final String subject, final String bodyText, final String from) throws NotesException {
final Session dominoSession = NotesFactory.createSession(dominoServer, dominoUsername, dominoPassword);
final Database dominoDb = dominoSession.getDatabase(dominoServer, dominoMailbox);
final Document mail = dominoDb.createDocument();
mail.appendItemValue("Form", "Memo");
mail.appendItemValue("Importance", "1");
mail.appendItemValue("Subject", subject);
mail.appendItemValue("Body", bodyText);
mail.replaceItemValue("From", from + "#NotesDomain");
mail.replaceItemValue("InetFrom", from);
mail.send(false, recipient);
dominoDb.recycle();
dominoSession.recycle();
}

Related

Java Mail: get UniqueID from Message

I need a uniqueID from a message Object to save this in my database.
Afterwards I´m able to search for this UID in my database and can add other properties, like "emailTrackingActive" etc.
a) Is there a possibility to get a whole UID for a Email Inbox or is it always only per folder? Currently I´m getting this as you can see in the code.
Currently I´m doing the following as you can see in the code:
After I´ve send the message, I copy the message into my "Sent" folder and then I want to get the UID and save it in the database.
With "EmailHelperClass" I´m getting Store etc.
I think it should be clear and I will not post this code...
private void copyIntoSentAndSaveInDatabase(EmailHelperClass email, final Message msg){
final Store store = email.getMailConfiguration().getWriteStore();
final Folder folder = (Folder) store.getFolder("Sent");
if (folder.exists() == false) {
folder.create(Folder.HOLDS_MESSAGES);
}
folder.open(Folder.READ_WRITE);
folder.appendMessages(new Message[] { msg });
// Get UniqueID
UIDFolder uf = (UIDFolder) folder;
Long messageId = uf.getUID(msg);
// Todo Update in DB etc
}
But now I´m getting the following error message:
java.util.NoSuchElementException: Message does not belong to this
folder
What is wrong here?
Hi all you need to change folder to IMAPFolder
final Store store = email.getMailConfiguration().getWriteStore();
final IMAPFolder folder = (IMAPFolder) store.getFolder("Sent");
folder.open(Folder.READ_WRITE)
with the help of this folder fetch all your messages i have write the below method to get the UID of the message
private long getMessagesUID(UIDFolder folder,javax.mail.message message){
try{
return folder.getUID(message)
}catch(Exception ex)
{
ex.printStackTrace();
}
Let me know in case of any query.

Spring Boot Thymeleaf JavaMail -"class path resource [images/logo.png] cannot be opened because it does not exist " with streams.foreach

I am using Spring Boot and Thymeleaf to send emails. I have one inline image as a signature in the email. Everything works fine if I send one email at a time. But, my use case is to send an individual email to a list of recipients. I am able to do that without the image. But, when I add the image, the first email is getting sent and for the second time I get class path resource [images/tp-logo.png] cannot be opened because it does not exist.
When I call emailService.send() from the stream.forEach() I get above error.
When I call it from a normal for loop, it works fine.
I understand that the streams are lazy, but why the resource is missing?
Working Caller method code:
for(ContactIfo contact : contactInfoList) {
ExecutorService emailExecutor = Executors.newCachedThreadPool();
emailExecutor.execute(() -> {
final String emailAddress = contact.getEmailAddress();
if (StringUtils.isNotBlank(emailAddress)) {
emailService.sendEmail(emailAddress);
}
});
}
Failing caller method code:
contactInfoList.parallelStream().forEach(contact -> {
ExecutorService emailExecutor = Executors.newCachedThreadPool();
emailExecutor.execute(() -> {
final String emailAddress = contact.getEmailAddress();
if (StringUtils.isNotBlank(emailAddress)) {
emailService.sendEmail(emailAddress);
}
});
});
Callee:
private void sendEmail(Mail mail) throws MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message,
MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
StandardCharsets.UTF_8.name());
Context context = new Context();
context.setVariables(mail.getProps());
String html = templateEngine.process("me-event-update-template", context);
helper.setText(html , true);
helper.setTo(mail.getMailTo());
helper.setSubject(mail.getSubject());
helper.setFrom(mail.getFrom());
// adding inline resources with matching cId to the variable name/value
helper.addInline("logo", new ClassPathResource("images/logo.png"), "image/png");
emailSender.send(message);
}

Google app engine entities are not being created

I am developing an android application using google endpoints and google app engine. My backend does not seem to actually be doing anything. It appears as if nothing is being saved to the datastore and therefore nothing can be retrieved from it.
Here are some of the Api methods I have written in endpoints that are not working:
private static String getUserId(User user) {
String userId = user.getUserId();
if (userId == null) {
AppEngineUser appEngineUser = new AppEngineUser(user);
ofy().save().entity(appEngineUser).now();
// Begin new session for not using session cache.
Objectify objectify = ofy().factory().begin();
AppEngineUser savedUser = objectify.load().key(appEngineUser.getKey()).now();
userId = savedUser.getUser().getUserId();
}
return userId;
}
#ApiMethod(name = "saveProfile", path = "profile", httpMethod = ApiMethod.HttpMethod.POST)
public Profile saveProfile(final User user, final ProfileForm profileForm) throws UnauthorizedException {
if(user == null) {
throw new UnauthorizedException("Authorization required.");
}
String firstName = profileForm.getFirstName();
String surname = profileForm.getLastName();
String userEmail = user.getEmail();
int year = profileForm.getYear();
int month = profileForm.getMonth();
int day = profileForm.getDay();
Profile profile = ofy().load().key(Key.create(Profile.class, getUserId(user))).now();
if (profile == null) {
// the user does not have a profile and is creating one for the first time
profile = new Profile(getUserId(user), firstName, surname, userEmail, year, month, day);
} else {
profile.update(firstName, surname, userEmail, year, month, day);
}
ofy().save().entity(profile).now();
return profile;
}
#ApiMethod(name = "getProfile", path = "profile", httpMethod = ApiMethod.HttpMethod.GET)
public Profile getProfile(User user) throws UnauthorizedException {
if (user == null) {
throw new UnauthorizedException("Authentication required.");
}
return ofy().load().key(Key.create(Profile.class, getUserId(user))).now();
}
}
The profile class has the #Entity annotation and is registered with objectify in a static block like so:
static {
factory().register(AppEngineUser.class);
factory().register(Profile.class);
}
The userId is generated by GAE through
com.google.appengine.api.users.User
and the userId property is a String with the #Index annotation.
I am also confused by the api explorer and how it is responding to these methods. Whenever I call the saveProfile api method, a profile object is returned with a userId of 0 and an email of "example#example.com" although I believe this is the default email when running on localhost.
I am also running api explorer over HTTP,Google says this "can cause problems." Is this the reason why nothing is working. I have had to load unsafe scripts just for me to use my api, but maybe it does not work as it is hosted over HTTP instead of HTTPS.
Is this entire problem of not being able to fully test my methods due to a fundamental flaw in my understanding of GAE or is due to me running on localhost. If it is the latter perhaps I should deploy to Appspot and things may run smoother.
If there is anything extra you need to help, please just ask.
Thank you!
Check your logs in the developers console. It records all API methods that you execute and will show if any have any errors.
Since you are getting example#example.com as the email of the User this leads me to believe the User is not being injected by GAE. This is probably because you are doing something wrong client side (e.g. in Android). Make sure your Android app correctly asks to log a user in with Google and pass those credentials to your builder object in Android.
If you are executing your API method via the api explorer, you need to be logged in as a google user first for that User object to be populated in your method (I think you already know that).
In short, check your logs and your client code.

Connect JIRA and retrieve Information

I have a Task that is to retrieve some Information from a JIRA account through Java. I downloaded the Jira API which is working with Java, but I have no idea how to make it work. I have to pass somewhere my username and password for log in and after that to retrieve what Information I want from what project I want.
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
URI uri = new URI(JIRA_URL);
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD);
// Invoke the JRJC Client
Promise<User> promise = client.getUserClient().getUser("admin");
// Here I am getting the error!!
User user = promise.claim();
///////////////////////////////////////
// Print the result
System.out.println(String.format("Your admin user's email address is: %s\r\n", user.getEmailAddress()));
// Done
System.out.println("Example complete. Now exiting.");
System.exit(0);
That above code is not working, because either if I pass a wrong password and a wrong username is showing me the same result. I have to know how to connect properly to JIRA and retrive some Information in JSON from there! Thank you for your time!
Here is the error
Caused by: com.atlassian.jira.rest.client.api.RestClientException: org.codehaus.jettison.json.JSONException: A JSONObject text must begin with '{' at character 9 of
I think you don't have the necessary permission to acces Jira , you have to connect with jira with an account that have the correct permissions!
The only thing I can think of is that you are sending incorrect creds. Try using the email address instead of just "admin".
Here is some code that might help: https://github.com/somaiah/jrjc
I check for an issue, but getting user info would be similar.
You can use the below code the get the results.Remember I am using this in my gradle project where I am downloading all the dependencies of JRCJ
import com.atlassian.jira.rest.client.api.JiraRestClientFactory
import com.atlassian.jira.rest.client.api.domain.User
import com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory
import com.atlassian.util.concurrent.Promise
/**
* TODO: Class description
*
* on 20 Jul 2017
*/
class Jira {
private static final String JIRA_URL = "https://JIRA.test.com"
private static final String JIRA_ADMIN_USERNAME = "ABCDE"
private static final String JIRA_ADMIN_PASSWORD = "******"
static void main(String[] args) throws Exception
{
// Construct the JRJC client
System.out.println(String.format("Logging in to %s with username '%s' and password '%s'", JIRA_URL, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD))
JiraRestClientFactory factory = new AsynchronousJiraRestClientFactory()
URI uri = new URI(JIRA_URL)
JiraRestClient client = factory.createWithBasicHttpAuthentication(uri, JIRA_ADMIN_USERNAME, JIRA_ADMIN_PASSWORD)
// Invoke the JRJC Client
Promise<User> promise = client.getUserClient().getUser(JIRA_ADMIN_USERNAME)
User user = promise.claim()
// Print the result
System.out.println(String.format("Your user's email address is: %s\r\n", user.getEmailAddress()))
// Done
//System.out.println("Example complete. Now exiting.")
//System.exit(0)
}
}

Fetch Friends profile image from restfb

I am using below code to get profile image of friends using Resfb. I get the response too with name id and image. Please some one help me asap on how to get the image from this data.
Code
Connection<User> myFriends = facebookClient.fetchConnection("me/friends", User.class,Parameter.with("fields", "id, name,picture"));
Response
"data":[{"id":"554603591","name":"Arjun Rao","picture":"http:\/\/profile.ak.fbcdn.net\/hprofile-ak-snc4\/211391_554603591_2022493_q.jpg"}"
Thanks
You can use restfb to parse Json-Objects:
JsonObject obj = new JsonObject(SERVER_RESPONSE);
try {
String pictureURL = obj.getString("picture");
}
catch(JsonException e) {
// key 'picture' not found
e.printStackTrace();
}
Could it be that RestFB isn't up to date in sense how Graph API returns (some objects) inside "data" object?
I managed to work-around with this custom class:
public class DataPictureHolder {
#Facebook("data")
public ProfilePictureSource picture;
}
You know how to parse the response?
If yes, just get the URL of the image, open a URLConnection and do a getInputStream() (the code for this is in this SO answer).
With the InputStream, you can save to a file or send it to the client.

Categories