Javamail SMTPSenderFailedException 553 - smtp

This code was working fine for months but has suddenly stopped working without any change in the code. The exception stack trace has:
com.sun.mail.smtp.SMTPSenderFailedException: 553 5.1.2 The address specified is not a valid RFC-5321 address. tj2sm1495299pab.4 - gsmtp
My code, which was working earlier:
final String username = uName;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.debug", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("<from email id>"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("<to email address>"));
message.setSubject("<subject>");
message.setContent(finalMessage, "text/html");
Transport.send(message);
} catch (MessagingException | UnsupportedEncodingException e) {
e.printStackTrace();
logger.error("Emailing error: "+e.getMessage());
}
This stopped working today.

What did it for me was changing the username-field content from "username" to "username#gmail.com".

change the "from email id" for the complete email adress
Google has change the last week the validation from standar RFC 5321 that covers the field "FROM"

Related

Restlet - JUnit - testing MULTIPART_FORM_DATA form Post

I was wondering what the best way to use JUnit to test a Resource for a Form post?
On a #Get I get service values via a Resource with the following:
#Test
public void testGetCollections() throws Exception {
String url ="http://localhost:14502/api/v1/collections";
Client client = new Client(Protocol.HTTP);
ChallengeResponse challengeResponse = new ChallengeResponse(ChallengeScheme.HTTP_BASIC,"user", "f399b0a660f684b2c5a6b4c054f22d89");
Request request = new Request(Method.GET, url);
request.setChallengeResponse(challengeResponse);
Response response = client.handle(request);
System.out.println("request"+response.getStatus().getCode());
System.out.println("request test::"+response.getEntityAsText());
assertEquals(200, response.getStatus().getCode());
ObjectMapper mapper = new ObjectMapper();
List<Collection> collectionList = mapper.readValue(response.getEntityAsText(), new TypeReference<List<Collection>>(){});
for(Collection collection : collectionList){
System.out.println("TITLE: "+collection.getTitle());
}
assertTrue(collectionList.size()>0);
}
On the #Post I'm trying to do the following:
#Test
public void testPostCollections() throws Exception {
String url ="http://localhost:14502/api/v1/collections";
Client client = new Client(Protocol.HTTP);
ChallengeResponse challengeResponse = new ChallengeResponse(ChallengeScheme.HTTP_BASIC,"user", "f399b0a660f684b2c5a6b4c054f22d89");
Request request = new Request(Method.POST, url);
ClientInfo info = new ClientInfo(MediaType.APPLICATION_JSON);
info.getAcceptedMediaTypes().add(
new Preference<MediaType>(MediaType.APPLICATION_JSON));
request.setClientInfo(info);
request.setEntity(
"collectionName=testCollection123&collectionDescription=testCollectionDescription123",
MediaType.MULTIPART_FORM_DATA);
request.setChallengeResponse(challengeResponse);
Response response = client.handle(request);
//boolean valid = false;
System.out.println("request"+response.getStatus().getCode());
System.out.println("request test::"+response.getEntityAsText());
assertEquals(200, response.getStatus().getCode());
}
I'm getting the following 500 error:
The server encountered an unexpected condition which prevented it from fulfilling the request.
BASED ON THE BELOW POSTED ANSWER I MADE THE FOLLOWING WORKING METHOD:
#Test
public void testAssetsPost() throws Exception {
ClientResource cr = new ClientResource("http://localhost:14502/api/v1/ass");
FormDataSet fds = new FormDataSet();
fds.getEntries().add(new FormData("metaData", "metaDataTest123"));
fds.setMultipart(true);
FormData fileRep = new FormData("file",
new FileRepresentation(new File("/Users/og/Documents/gump.jpg"),
MediaType.IMAGE_JPEG));
fds.getEntries().add(fileRep);
FormData fileRep2 = new FormData("associatedDoc",
new FileRepresentation(new File("/Users/og/Documents/gump.jpg"),
MediaType.IMAGE_JPEG));
fds.getEntries().add(fileRep2);
Representation r = null;
try{
r = cr.post(fds);
} catch (ResourceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println( "Got Context: " + cr.getContext() );
System.out.println( "Got Response: " + cr.getResponse());
System.out.println( "Got Resonse Attribute : " + cr.getResponseAttributes() );
System.out.println( "Got Resonse Entity: " + cr.getResponseEntity() );
System.out.println("Got response !! , response : " + r.getText());
System.out.println(r.getText());
}
I don't know what is exactly the error you encountered within your server application. I would be interesting if we could have a stacktrace.
That said, you can build programmatically HTML forms using the org.restlet.ext.html extension. For more details, you could read this blog post: http://restlet.com/blog/2015/10/27/implementing-file-upload-with-restlet-framework/.
At a first sight, the media type isn't correct since you don't send a multipart form but a simple form. So you should use MediaType.APPLICATION_WWW_FORM instead of MediaType.MULTIPART_FORM_DATA.
A sample for a form containing a file:
Form fileForm = new Form();
fileForm.add(Disposition.NAME_FILENAME, "myimage.png");
Disposition disposition = new Disposition(Disposition.TYPE_INLINE, fileForm);
FileRepresentation entity = new FileRepresentation(f, MediaType.IMAGE_PNG);
entity.setDisposition(disposition);
And for a simple form:
FormDataSet fds = new FormDataSet();
fds.setMultipart(true);
FormData fdFile = new FormData("fileToUpload", entity);
fds.getEntries().add(fdFile);
FormData fdValue = new FormData("field", "value");
fds.getEntries().add(fdValue);
Hope it helps you,
Thierry

MySql Query Sent by Email

I have a simple query that select some fields from a few different tables and I need it to run once a month. I know i can schedule a monthly "job" with the CREATE EVENT, however, is it possible to have that information emailed to some addresses after the query runs? That way i don't need to log into the server and look at the new file?
I think that Mysql doesn't support Email sending.
In this case, you can develop an auxiliary program that sends the file created, and execute it with - scheduled task, Cron ...(It depends on the Operating System of the server you're using).
The auxiliary program can be like this code adding the file/s you want to attach (attachFiles variable).
public class EmailAttachmentSender {
public static void sendEmailWithAttachments(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message, String[] attachFiles)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFiles != null && attachFiles.length > 0) {
for (String filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
/**
* Test sending e-mail with attachments
*/
public static void main(String[] args) {
// SMTP info
String host = "smtp.gmail.com";
String port = "587";
String mailFrom = "your-email-address";
String password = "your-email-password";
// message info
String mailTo = "your-friend-email";
String subject = "New email with attachments";
String message = "I have some attachments for you.";
// attachments
String[] attachFiles = new String[3];
attachFiles[0] = "e:/Test/Picture.png";
attachFiles[1] = "e:/Test/Music.mp3";
attachFiles[2] = "e:/Test/Video.mp4";
try {
sendEmailWithAttachments(host, port, mailFrom, password, mailTo,
subject, message, attachFiles);
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Could not send email.");
ex.printStackTrace();
}
}
Mysql does not support that functionality.
You can use a cron job (Quartz) to schedule a job every month,
where you can fetch the data and shoot an email containing your data.
Refer the below link for quartz job :
http://www.mkyong.com/java/example-to-run-multiple-jobs-in-quartz/
is it possible to have that information emailed to some addresses
after the query runs?
If you are looking for a MySQL built in solution then probably NO. This particular should be handled in application end.
So, if you are scheduling the query as cron job in linux (OR) batch job in windows then you can configure cron (or) batch to send an email to list of recipients once the query finishes.
How to configure cron to send mail can be checked HERE
I haven't done this myself but I see no reason why it shouldn't work: create a UDF (user defined function) that takes the e-mail parameters and sends out the e-mail. You can write UDFs e.g. in C++ and have so all necesssary libraries at hand.

Send Email using gmail SMTP throwing AuthenticationFailedException

I am sending mail using smtp from my web site to gmail.its work well localy. But did't work in remote server
i am previously using this code:
public boolean sendMail(String subject, String bodyContent,String emailAddress){
boolean isMailsent=false;
final String SMTP_HOST= getText("email.smtp.host");
final String SOCKET_FACTORY_PORT= getText("email.socket.factory.port");
final String SMTP=getText("email.smtp.port");
final String MAIL_USER_EMAIL_ADDRESS=getText("email.username");
final String MAIL_USER_PASSWORD= getText("email.password");
final String EMAIL_FROMNAME= getText("email.fromname");
try{
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.socketFactory.port",SOCKET_FACTORY_PORT);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", SMTP);
Authenticator auth = new SMTPAuthenticator(MAIL_USER_EMAIL_ADDRESS, MAIL_USER_PASSWORD);
Session session = Session.getInstance(props, auth);
Message message = new MimeMessage(session);
InternetAddress from = new InternetAddress(MAIL_USER_EMAIL_ADDRESS,EMAIL_FROMNAME);
message.setFrom(from);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress));
message.setSubject(subject);
message.setContent(bodyContent,"text/html" );
Transport.send(message);
isMailsent=true;
}catch(Exception e){
LOGGER.error(e);
}
return isMailsent;
}
how to fix it please give me best example
You need to provide the correct GMail credentials to authenticate.

Send javamail using Office365

I'm having trouble configuring the SMTP settings for sending mail using javax.mail (1.4.4) through Office365, so I thought I'd post the properties here for others.
Use Office365 smtp details as below:
private static Properties props;
private static Session session;
static {
props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.host", "m.outlook.com");
props.put("mail.smtp.auth", "true");
session = Session.getInstance(props, new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("office365 email address",
"office365 password");
}
});
}
And with spring-boot, you simply need to add this to your application.properties:
spring.mail.host = smtp.office365.com
spring.mail.username = mathieu.pousse#headquarter.com
spring.mail.password = s3cr3t
spring.mail.port = 587
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable = true
A working code example:
Email email = new SimpleEmail();
email.setHostName("smtp.office365.com");
email.setSmtpPort(587);
email.setAuthenticator(new DefaultAuthenticator("a#b.com", "****"));
email.setStartTLSEnabled(true);
try {
email.setFrom("a#b.com");
email.setSubject("Job Failure");
email.setDebug(true);
email.setMsg("This is a test mail ... :-)" );
email.addTo("a#y.com");
email.send();
} catch (EmailException e) {
e.printStackTrace();
}
The only error that I am noticing in your code is the incorrect Host
javaMailProperties.setProperty("mail.smtp.from", "abc#c.com");
javaMailProperties.setProperty("mail.smtp.user", "abc#c.com");
javaMailProperties.setProperty("mail.smtp.password","Password");
javaMailProperties.setProperty("mail.smtp.host", "smtp.office365.com");
javaMailProperties.setProperty("mail.smtp.port", "587");
javaMailProperties.setProperty("mail.smtp.auth", "true");
javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
Change the host you will be all good.

how to send HTML email

I have to send HTML file via email but not as attachment.
Message simpleMessage = new MimeMessage(mailSession);
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It is sending email simply with text message.
I want to send HTML content which is stored in another file but not as attachment
Don't upcast your MimeMessage to Message:
MimeMessage simpleMessage = new MimeMessage(mailSession);
Then, when you want to set the message body, either call
simpleMessage.setText(text, "utf-8", "html");
or call
simpleMessage.setContent(text, "text/html; charset=utf-8");
If you'd rather use a charset other than utf-8, substitute it in the appropriate place.
JavaMail has an extra, useless layer of abstraction that often leaves you holding classes like Multipart, Message, and Address, which all have much less functionality than the real subclasses (MimeMultipart, MimeMessage, and InternetAddress) that are actually getting constructed...
Here is my sendEmail java program. It's good to use setContent method of Message class object.
message.setSubject(message_sub);
message.setContent(message_text, "text/html; charset=utf-8");
sendEmail.java
package employee;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
public class SendEmail {
public static void sendEmail(String message_text, String send_to,String message_sub ) throws UnsupportedEncodingException {
final String username = "hello#xyz.com";
final String password = "password";
Properties prop = new Properties();
prop.put("mail.smtp.host", "us2.smtp.mailhostbox.com"); //replace your host address.
prop.put("mail.smtp.port", "587");
prop.put("mail.smtp.auth", "true");
prop.put("mail.smtp.starttls.enable", "true"); //TLS
Session session = Session.getInstance(prop,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender#xyz.com", "Name from which mail has to be sent"));
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(send_to)
);
message.setSubject(message_sub);
message.setContent(message_text, "text/html; charset=utf-8");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}