Not able to view 'To' field using java mail API - java

I am trying to fetch/read my email using java mail API.
I am using following line to read the 'To' field
System.out.println("TO:" + message.getRecipients(Message.RecipientType.TO));
And it is giving the following output :
TO:[Ljavax.mail.internet.InternetAddress;#6e1567f1
where as I want the output like
xyz#gmail.com

Try it:
Address[] recipients = message.getRecipients(Message.RecipientType.TO);
for(Address address : recipients) {
System.out.println("TO:" + address.toString());
}

message.getRecipients(Message.RecipientType.Io)) returns an array of message.
Retrive a value from message array sample code snippet.
Address[] recipients = message.getRecipients(Message.RecipientType.TO);
for(Address address : recipients){
System.out.println(address.toString());
}

Related

Java - How to get only message body from FileDescriptorProto

I am trying to print contents of message body of proto file. But my code below is printing details of import too which I don't want. Any suggestion on how to filter this so that only message contents will be printed.
FileInputStream fin = new FileInputStream("mymessages.desc");
Descriptors.FileDescriptorSet set = Descriptors.FileDescriptorSet.parseFrom(fin);
for(FileDescriptorProto fileDesc : set.getFileList()){
List<DescriptorProto> descList = fileDesc.getMessageTypeList();
for(DescriptorProto desc : descList ){
System.out.Println(desc) ; // print all proto info including the imported field as well as message
}
}
}
My proto file
syntax = "proto3"
import "validate.proto";
message User{
string firstName = 1;
string lastName = 2;
}
You could just delete the header lines:
System.out.println(desc.replaceAll("(?sm)\\A.*?(?=^message)", ""));
The regex (?sm)\\A.*?(?=^message) matches everything from start up to, but not including, the first line that starts with message, which is replaced with a blank (ie deleted).

parsing email in java returns no entry

currently I'm creating an email service for my hobby project for newly signed up users. This is the relevant part of the code, which causes me some headache:
private Message createEmail(String firstName, String password, String email) throws MessagingException {
Message message = new MimeMessage(getEmailSession());
message.setFrom(new InternetAddress(FROM_EMAIL));
message.setRecipient(Message.RecipientType.TO, InternetAddress.parse(email, false)[0]);
message.setRecipient(Message.RecipientType.CC, InternetAddress.parse(CC_EMAIL, false)[0]);
message.setSubject(EMAIL_SUBJECT);
message.setText("Hello " + firstName + ", \n \n Your new account password is: " + password + "\n \n " +
"The support team");
message.setSentDate(new Date());
message.saveChanges();
return message;
}
I have two problems with this line message.setRecipient(Message.RecipientType.TO, InternetAddress.parse(email, false)[0]); (and of course the same problem with the next line below it):
On the internet, if I google after it, everywhere it is used like this:
message.setRecipient(Message.RecipientType.TO, InternetAddress.parse(email, false);
so, without the indexing. But if I remove the indexing, I get an IDE error, which says, that the function requires a type of Address, but it has got InternetAddress[], an array. That's why I put the indexing.
But if I leave the indexing and run the app and register a new user, I get the error in the console: Index 0 out of bounds for length 0. Obviously, the InternetAddress[] array is empty. But why?
What exactly is going on here?
Looking at the docs, it should be new InternetAddress(String, boolean), which
Parse[s] the given string and create[s] an InternetAddress.
instead of InternetAddress.parse(String, boolean), which
Parse[s] the given sequence of addresses into InternetAddress objects.

"Mailbox does not exist." when fetching emails on EWS

I am trying to access emails on a Office365 mailbox, using Exchange Web Services (EWS).
My O365 admin has created :
the shared mailbox : shared#domain.com
the account : my.account#domain.com
a group, giving access to the account on the mailbox
I am able to retrieve the Oauth token using the appId/tenantId and a UserNamePasswordParameters using the account's credentials, and now I am trying to retrieve the emails from the mailbox, but I get this error :
microsoft.exchange.webservices.data.core.exception.service.remote.ServiceResponseException:
Mailbox does not exist.
here's my code :
public Iterable fetchEmails(String token, String account) throws Exception {
if(token==null) {
token = getToken();
}
FindItemsResults<Item> emails;
try (ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2)) {
service.getHttpHeaders().put("Authorization", "Bearer " + token);
service.setUrl(new URI("https://outlook.office365.com/EWS/Exchange.asmx"));
service.setWebProxy(new WebProxy(PROXY_HOST, PROXY_PORT));
FolderId folder = new FolderId(WellKnownFolderName.Inbox, new Mailbox(account));
emails = service.findItems(folder, new ItemView(15));
}
return emails;
}
OK, it was a bit stupid.. I got confused because the account is also an email..
solution is to pass the mailbox (shared#domain.com) instead of the account (my.account#domain.com) when building the Mailbox object :
FolderId folder = new FolderId(WellKnownFolderName.Inbox, new Mailbox("shared#domain.com"));
And now it's working, I am able to get the emails.

Adding roles to a mentioned user in JDA

I want to be able to run a command that begins with !suspend, mentions a user, then determines a time length and adds a role named 'Suspended' to the mentioned user for the specified time length.
Message message = event.getMessage(); //Sets the message equal to the variable type 'Message' so it can be modified within the program.
String content = message.getContentRaw(); //Gets the raw content of the message and sets it equal to a string (best way to convert types Message to String).
MessageChannel channel = event.getChannel(); //Gets the channel the message was sent in (useful for sending error messages).
Guild guild = event.getGuild();
//Role group = content.matches("((Suspended))") ? guild.getRolesByName("Suspended", true).get(0) : null;
if(content.startsWith("!suspend"))//Pretty self explanatory. Enters the loop if the message begins with !suspend.
{
String[] spliced = content.split("\\s+"); //Splits the message into an array based on the spaces in the message.
TextChannel textChannel = event.getGuild().getTextChannelsByName("ranked-ms_punishments",true).get(0); //If there is a channel called ranked-ms_punishments which there should be set the value of it equal to the variable.
int length = spliced.length;//Sets 'length' equal to the number of items in the array.
if(length == 3)//If the number of items in the array is 3 then...
{
if(spliced[1].startsWith("<"))
{
list.add(spliced[1]);
String tempuser = spliced[1];
textChannel.sendMessage(tempuser + " you have been suspended for " + spliced[2] + " days.").queue();//Sends the message in the quotations.
//add role to the member
}
}else {
channel.sendMessage("Please use the following format for suspending a user: '!suspend' <#user> (length)").queue(); //If length doesn't equal 3 then it sends the message in quotations.
}
}
Not sure how to do this, as I'm too unfamiliar with JDA to make it work. I have everything working except for the actual addition of the role named 'Suspended'.
Adding a role to the mentioned members in a message can be done as follows:
Role role = event.getGuild().getRolesByName("Suspended", false).get(0);
List<Member> mentionedMembers = message.getMentionedMembers();
for (Member mentionedMember : mentionedMembers) {
event.getGuild().getController().addRolesToMember(mentionedMember, role).queue();
}
Note that your bot will need the MANAGE_ROLES permission to add roles.
You can do this: 👍
event.getGuild().addRoleToMember(memberId, jda.getRoleById(yourRole));
event.getGuild().addRoleToMember(member, event.getGuild().getRoleById(yourRole)).queue();

JavaMail Send emails in the same thread/conversation

Our application send emails automatically, and I need those emails to be grouped in threads, so the user have them organized in their mailboxes. These emails could have different subjects as well. For example:
Issue 93 created
Issue 93 description changed
Issue 93 assignee changed
Issue 94 created
Issue 94 closed
I'm trying to set the "In-Reply-To" header of every child email to point to the parent mail Message-ID. So, every time a new issue is created, and the first mail is sent, I will save its Message-ID. When a new email related to the issue is going to be sent, I will add a "In-Reply-To" header, pointing to the saved Message-ID.
My code looks like this:
Message message = new CustomMessage(session, parentMessageId);
message.setFrom(new InternetAddress("from#mycompany.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to#customer.com"));
message.setSubject("Issue " + id + " " + actionPerformed);
message.setText(content);
message.saveChanges();
Transport.send(message);
Class CustomMessage looks like this:
public class CustomMessage extends MimeMessage {
private String inReplyTo;
public CustomMessage(Session session, String inReplyTo) {
super(session);
this.inReplyTo = inReplyTo;
}
#Override
public void saveChanges() throws MessagingException {
if (inReplyTo != null) {
// This messageID is something like "<51228289.0.1459073465571.JavaMail.admin#mycompany.com>" including <>
setHeader("In-Reply-To", inReplyTo);
}
}
}
The problem is the email is sent, but is not grouped in threads. I have noticed that they are grouped correctly if they have the same subject, but I need different subjects for every email.
Is this actually possible with different subjects? Do I need to use a different strategy?
Thanks
It depends on the "threading" algorithm used by whichever mail reader is being used. As the creator of the messages you don't have absolute control over how they're displayed.

Categories

Resources