parsing email in java returns no entry - java

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.

Related

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.

Gmail API java update draft using MimeMessage

Google provides the following code to get a gmail draft
public static Draft getDraft(Gmail service, String userId, String draftId)
throws IOException {
Draft draft = service.users().drafts().get(userId, draftId).execute();
Message message = draft.getMessage();
System.out.println("Draft id: " + draft.getId() + "\nDraft Message:\n"
+ message.toPrettyString());
return draft;}
My question is : Can I get a MimeMessage from the Message? If I could, I would update this MimeMessage with multiple attachments. Or if anyone else knows how to update a draft with multiple attachments, please advice.

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

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());
}

Jain SIP get user name

I need to get the extension number from the "From header", I have tried everything but nothing worked.
Even tried to do:
byte[] raw = req.getRawContent();
And manually find the From and the number, But that returned null
What am I doing wrong? How to get that number
Get the FromHeader and then extract the information you need from it. For instance, if the extension is the user part of the URI:
FromHeader fromHeader = (FromHeader) req.getHeader("From");
Address fromAddress = fromHeader.getAddress();
URI fromURI = fromAddress.getURI();
if (fromURI.isSipURI()) {
SipURI fromSipURI = (SipURI) fromURI;
extension = fromSipURI.getUser();
}
Did you saw the javadoc?
The method getRawContent() return a message content as a raw byte array, or null if no content is set
Can you explain again your question? Maybe I can help you.

Categories

Resources