I'm creating a program in Java to alert a user if they get an email about a password reset. I have sent an email to myself with the text "Your password has been reset" and created a method that analyzes the email:
private static boolean passwordResetFinder(String email) {
boolean passReset = false;
if (email.matches(".*password.*") && (email.matches(".*changed.*") || email.matches(".*reset.*"))) {
passReset = true;
}
and I call the method like this:
String email = new String();
...
open connection to inbox using JavaMail
...
Object content = emailReader.getContent();
email = content.toString();
if(passwordResetFinder(email)) {
System.out.println("Password Alert");
}
And this doesn't work. However if I put the following:
if (passwordResetFinder("Your password has been reset")
or
email = content.toString();
email = "Your password has been reset";
if(passwordResetFinder(email))
it works. Why is this?
Maybe the toString() of the Object returned by emailReader.getContent() does not give you a String-representation of the text the mail contains. This might be the case if it is a subclass of Multipart when reading
multipart mails or a Stream if the type of the message is unkown.
Return the content as a Java object. The type of the returned object is of course dependent on the content itself. For example, the object returned for "text/plain" content is usually a String object. The object returned for a "multipart" content is always a Multipart subclass. For content-types that are unknown to the DataHandler system, an input stream is returned as the content
https://javamail.java.net/nonav/docs/api/javax/mail/Part.html#getContent%28%29
Related
I want to write a service through which I can create a email message with (to, cc, bcc, subject, body) specified. Then I need to return this email message to front end and download it in ".oft" format, in such a way that when I click on this downloaded file; file should open with all the fields (to, cc, bcc, subject, body) populated.
I am using Java as backend technology and angular5 as front-end.
I have tried using javax.mail utility to create the email message and return it as byte array. Something like:
Properties prop = System.getProperties();
Session session = Session.getDefaultInstance(prop, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("emailAddr#domain.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("emailAddr#domain.com"));
msg.setSentDate(new Date());
msg.setSubject("subject");
msg.setText("text of msg");
//return it from service API as
response.getOutputStream().write(msg.toString().getBytes());
On front end (component.ts file) I am retrieving the response as :
//function gets called on button click
createEmailTemplate():void{
this.httpService.getEmail('serviceUrl')
.subscribe(
email => {
let filename = "SampleMailFile.oft";
let linkElement = document.createElement('a');
let blob = new Blob([email], { type: "message/rfc822"});
let url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", filename);
let clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
}
);
}
A MSG file is supposed to have the same format as an OFT file. If that’s true then you should be able to use jotlmsg to generate the file. You shouldn’t need to use JavaMail at all for this, since it’s intended to actually send the mail.
NOTE: I’ve not used this library before, so I can’t speak to whether this will truly work.
SO i'm making a mail client for a homework assignment and one of the requirements is to handle incoming attachments. The first thing I want to do is just show if an email even has an attachment or not. I have a bunch of AWT lists that are side by side for From, Subject, Size, Date, Attachment.
For testing purposes, if the disposition returns null, i just put an x in the attachmentList. If its inline, it puts an i and for attachments it should show the filename. However, even on emails where there are attachments and looking at the headers in gmail webmail, which shows the content disposition as attachment (all lower case), the getDisposition of the email still returns null. I don't get why its not returning ATTACHMENT or attachment or something besides null. Here is the relevant code.
for (int i = 0; i < messages.length; i++) {
Address[] froms = messages[i].getFrom();
String email = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
fromList.add(email);
subjectList.add(messages[i].getSubject());
sizeList.add("" + messages[i].getSize());
dateList.add(messages[i].getReceivedDate().toString());
String disposition = messages[i].getDisposition();
System.out.println("Disposition is " + disposition + ".");
if (disposition == null) {
attachmentList.add("x");
}
else if ("INLINE".equalsIgnoreCase(disposition)) {
attachmentList.add("i");
}
else if ("ATTACHMENT".equalsIgnoreCase(disposition)) {
String fileName = messages[i].getFileName();
if (fileName != null) {
attachmentList.add("attachment " + fileName);
}
}
}
You'll notice that it prints "the disposition is..." which is another testing code and it always prints either null or INLINE. The particular email i'm looking at is about 700k and contains 2 attachments.
Look at the raw MIME text of the message and make sure the Content-Disposition header is set as you expect.
Turn on JavaMail session debugging and examine the protocol trace in the debug output.
Are you using IMAP to read the message? If so, the IMAP server parses the message and returns the "disposition" information in the IMAP protocol message. The IMAP server may not be parsing the message correctly or may not be returning the disposition information correctly.
I have got few things to work e.g. Using -
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
I am able to get all the details of the user, name, User ID etc.
My Problem is how to take all this information to the server "safely". I don't want this information to be sniffed on its way to server. I use JAVA(Servet/JSP) language, PLEASE HELP ME ON THIS. I wish there was some way like registration plugin where Facebook sends all the information on a redirect_url link.
Regards,
Jagpreet Singh
EDIT: If anybody requires the Java Code -
// it is important to enable url-safe mode for Base64 encoder
Base64 base64 = new Base64(true);
// split request into signature and data
String[] signedRequest = request.getParameter("signed_request").split("\\.", 2);
logger.info("Received signed_request = " + Arrays.toString(signedRequest));
// parse signature
String sig = new String(base64.decode(signedRequest[0].getBytes("UTF-8")));
// parse data and convert to JSON object
JSONObject data = (JSONObject) JSONSerializer.toJSON(new String(base64.decode(signedRequest[1].getBytes("UTF-8"))));
logger.warn("JSON Value = " + data);
// check signature algorithm
if (!"HMAC-SHA256".equals(data.getString("algorithm"))) {
// unknown algorithm is used
logger.error("HMAC-SHA256 Algo? = false, returning ERROR");
return ERROR;
} else {
logger.error("HMAC-SHA256 Algo? = true, Checking if data is signed correctly...");
}
// check if data is signed correctly
if (!hmacSHA256(signedRequest[1], fbSecretKey).equals(sig)) {
// signature is not correct, possibly the data was tampered with
logger.warn("DATA signed correctly? = false, returning ERROR");
return ERROR;
} else {
logger.warn("DATA signed correctly? = true, checking if user has authorized the APP...");
}
// check if user authorized the APP (FACEBOOK User)
if (!data.has("user_id") || !data.has("oauth_token")) {
// this is guest, create authorization url that will be passed
// to javascript
// note that redirect_uri (page the user will be forwarded to
// after authorization) is set to fbCanvasUrl
logger.warn("User has authorized the APP? = false, returning ERROR");
return ERROR;
} else {
logger.warn("User has authorized the APP? = true, Performing User Registration...");
// this is authorized user, get their info from Graph API using
// received access token
// String accessToken = data.getString("oauth_token");
// FacebookClient facebookClient = new
// DefaultFacebookClient(accessToken);
// User user = facebookClient.fetchObject("me", User.class);
}
Facebook sends a signed_request parameter when you authenticate with a client-side method. You can pass this to your server, authenticate it, and then unpack it to get at the information you need. It is encrypted with your app secret, so you can be sure that it is secure.
See the signed_request documentation for more information.
I am using Amazon Simple Email Service java API to send mail to receivers.
I am sending URL in mail body inside tag.
My use case demands the user to double click on the URL received to prompt some action. (like confirmation mail)
Problem is the url gets encoded while receiving. On double clicking it gives page not found (404) error.
Original URL : http://something.com/confirm/email=abc#hotmail.com®Key=somekey&confirm=true
When i double click on this URL on mail, the link is opened in address bar as :
http://something.com/confirm/email=abc%40hotmail.com%26regKey=somekey%26confirm=true
I am using AmazonSimpleEmailServiceClient. Code is below :
SendEmailRequest request = new SendEmailRequest().withSource(sourceAddress);
String confirmationURL="http://something.com/confirm/email=abc#hotmail.com®Key=somekey&confirm=true";
List<String> toAddresses = new ArrayList<String>();
toAddresses.add(toEmail);
Destination dest = new Destination().withToAddresses(toAddresses);
request.setDestination(dest);
Content subjContent = new Content().withData("Confirmation Request");
Message msg = new Message().withSubject(subjContent);
// Include a body in both text and HTML formats
Content textContent = new Content().withData("Dear please go to the following URL:"+
confirmationURL+"\n\n");
Content htmlContent = new Content().withData("<p>Dear please go to the following URL:</p>"+
"<p>"+confirmationURL+"</p>");
Body body = new Body().withHtml(htmlContent).withText(textContent);
msg.setBody(body);
request.setMessage(msg)
UPDATE
Just found, this problem is occurring only when recipient email is in hotmail.com. Why microsoft always have to do something differently ? Somebody help !
Use the class java.net.URLEncoder:
String confirmationURL = URLEncoder.encode( "http://something.com/confirm/email=abc#hotmail.com®Key=somekey& confirm=true", "UTF-8");
Can someone tell me how to insert newline characters in email content. I use this code snippet to send emails.
public boolean sendMail(final Account player, final Object tl, final String type)
{
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception
{
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
String msgAdmin = msgFrom;
message.setTo(player.getEmail()); // TODO: changed from msgAdmin to player.getEmail()
message.setFrom(msgFrom);
message.setSubject(type + " invitation");
Map model = new HashMap();
model.put("tl", tl);
model.put("player", player);
model.put("type", type);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
"com/test/mail/invite.vm", model);
logger.debug(text);
message.setText(text, true);
}
};
return sendMail(preparator);
}
I tried \r\n characters in the email content. But it doesn't seem to work. HTML markup like BR tag works, but i dont want to add html markups in the email content. Any other solution is possible?
Actually the problem is when you are invoking the message.setText, you are setting the second arguement to true. Which means the message is interpreted as HTML. In order for the emails newlines to show, just set that second argument to false.
Newline characters and velocity templates is a well-documented problem. The best workaround is to stash "\n" as a value of a property that you make available to template. Then reference that property.