Issue attaching zip file in javamail - java

I was trying to attach a zip file using javamail and was getting the below error :
"com.sun.mail.smtp.SMTPSendFailedException: 552-5.7.0 This message was blocked because its content presents a potential
552-5.7.0 security issue. Please visit http://support.google.com/mail/bin/answe
552-5.7.0 r.py?answer=6590 to review our message content and attachment content
552 5.7.0 guidelines. vb7sm60966875pbc.13 - gsmtp"
Attaching a doc or xls has got no issues. I even believe that attaching a zip file is no different from any other file. Please let me know what is the issue here.
I have also provided the code if needed.
public class SendMail {
#Test
public static void sendFileEmail()
{
// Recipient's email ID needs to be mentioned.
String to = "*****#gmail.com";
// Sender's email ID needs to be mentioned
String from = "****#gmail.com";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");
properties.put("mail.debug", "false");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("*****#gmail.com","****");
}
});
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "XSLTReports.zip";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}

I guess you have not set MIME type for the multipart attachements that you send. Try to set it and see
The standard MIME type for ZIP files is application/zip.
Also try application/octet-stream if it dosen't work

I believe the issue was some how related to content of the zip file . I changed the zip file and it is working fine

Please make sure that network access is OK, The problem seems to be network access permission
First : try to ping from your machine to mail server if ok, it's visable to you
Second : try to send simple mail (subject/content)
Third : try to attach simple doc (txt file)

Related

Javamail adding attachment prevent mail to be sent

I'm struggling with Javamail, I'm trying to send emails with a zip file attached.
When I try to send a mail without attachment, it works fine but when I add the zip the mail is no longer sent. I have no errors...
My code :
LOGGER.info("########################### Send Email with attachement to " + destination + " Start ######################");
//Config smtp mail
Properties props = new Properties();
props.put("mail.smtp.host", getSmtpHost());
props.put("mail.smtp.socketFactory.port", getSmtpsocketFactoryPort());
props.put("mail.smtp.socketFactory.class", getSmtpsocketFactoryClass());
props.put("mail.smtp.auth", getSmtpAuth());
props.put("mail.smtp.port", getSmtpPort());
//instance Session
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(getUsername(), getPassword());
}
});
try {
//construction objet mail
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(getFromAddress()));
//Send Email to Addresse
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination));
message.setSubject(objet);
message.setSentDate(new Date());
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(contenu);
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
String fileName = attachementPath + attachementName;
File file = new File (fileName);
attachmentBodyPart.attachFile(file);
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentBodyPart);
message.setContent(multipart);
//send Email
Transport.send(message);
LOGGER.info("########################### Send email with attachement to " + destination + " End ########################### ");
} catch (MessagingException e) {
LOGGER.error("Error when send email to " + destination);
throw new RuntimeException(e);
}
I've tryied a lot of things, I may be to tired to find the mistake xD
Thanks for the help !!
Update : Thanks to jmehrens I've found the issue. My mail server doesn't allow .zip
Make sure your mail server doesn't have a policy in place that prevents the delivery of emails with the extension of .zip. You should be able to test that with just a mail client (or JavaMail) and rename the extension to either .txt or even .piz.
Read the JavaMail FAQ. It is full of good information on best practices, debugging and troubleshooting steps.

getting syntax error in property.setProperty("mail.smtp.host",host);

I am getting the syntax for the below line while trying to send the mail through SMTP .I tried in google but didnt get any relevant answer.
property.setProperty("mail.smtp.host",host);
CODE:
public class SendMail {
//Recipient Mail id
String to = "Receiver Mail ID";
//Sender Mail Id
String from = "Sender Mail ID";
//Sending email from the localhost
String host = "localhost";
//Get System Properties
Properties property = System.getProperties();
//Setup the mail server
property.setProperty("mail.smtp.host",host);
property.setProperty("mail.smtp.port" , "465");
//property.put("mail.smtp.auth", "true");
//Get the default session object
Session session = Session.getDefaultInstance(property);
try
{
//Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
//Set From: header field of the header
message.setFrom(new InternetAddress(from));
//Set To : header field of the header
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
//Set Subject : header field
message.setSubject("Automation Testing Report");
//Create the Message part
BodyPart messageBodypart = new MimeBodyPart();
//Enter the message in the Mail Body
messageBodypart.setText("***********Find the below for the Report****************");
//Create a Multipart Message
Multipart multipart = new MimeMultipart();
//Set Text message part
multipart.addBodyPart(messageBodypart);
//Part two is attachment
/*create the Message part*/
messageBodypart = new MimeBodyPart();
String filename = "E:\\Project\\jar\\Selenium Scripts\\Hybrid_Driven\\test-output\\emailable-report.html";
DataSource source = new FileDataSource(filename);
messageBodypart.setDataHandler(new DataHandler(source));
messageBodypart.setFileName(filename);
//set the text message part
multipart.addBodyPart(messageBodypart);
//Send the complete message part
message.setContent(multipart);
//Send message
Transport.send(message);
System.out.println("Mail has sent successfully");
}
catch(MessagingException mex)
{
mex.printStackTrace();
}
}
}
Please help me to resolve this issue.
You cannot put java code directly into a class. It needs to be within methods. The following is happily accepted by the compiler:
public class SendMail {
...
//Get System Properties
java.util.Properties property = System.getProperties();
void doSomething()
{
property.setProperty("mail.smtp.host", host);
property.setProperty("mail.smtp.port", "465");
...
}
}

Error when sending Mail and attachment in Java

I have a function to send mail with attachment in java. It works when i uploaded the attachment. However, the problem is that if i have to send a mail without attachment, it says error when i send a mail and i did not upload any attachment.
here is my code:
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
String html = text;
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("abdool.latiff#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(email));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(html, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
String filename = "C:/Users/gro/Desktop/"+attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
any idea how i can solve this?
i get this error:
org.apache.jasper.JasperException: java.lang.RuntimeException: javax.mail.MessagingException: IOException while sending message;
nested exception is:
java.io.FileNotFoundException: C:\Users\gro\Desktop (Access is denied)
Its just not able to find the file..
I am not sure where you are getting the attachment field set.
But, wrapping the fragment of code that is attaching the file to message, something like this below should work for you:
if(attachment != null && attachment.length() > 0) {
messageBodyPart = new MimeBodyPart();
String filename = "C:/Users/gro/Desktop/"+attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
I don't quite understand your implementation as the filename is set within the code without any user interaction. I suggest you change the body a little bit to get something like:
if(filename!=null) {
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
Let me see if I understand, you get this when you try to sent an email without attachment??
So the variable "attachment" is null??
So you are trying to load the file "C:/Users/gro/Desktop/null"??
And you are get a FileNotFoundException for that?? -.-
Without seeing what "attachment" is, it is going to be hard to figure out what you are doing. As others have already mentioned above, you need to check the value of "attachment" and if it exists (non-null or File.exists()) then the block of code for attaching the file to email should be executed.
Can you please hardcode the file path (including file name) and try the operation, I think your 'attachement' is either getting set to null or some non existing directory.

send html page as email in java

I am trying to send html page as message.
already send html email through message.setContent("<html><body><h1>This is actual message</h1></body></html>","text/html" ); these method .Now iwant to send a html page .
like message.setContent("street.html","text/html" );
how to send these below is my full code
String to = "to#gmail.com";
String from = "from#gmail.com";
Properties properties = System.getProperties();
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("from#gmail.com", "from2013");
}});
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setContent("street.html","text/html" );
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
A short one-liner for this one:
StringWriter writer = new StringWriter();
IOUtils.copy(new FileInputStream(new File("home.html")), writer);
message.setContent(writer.toString(), "text/html");
NOTE:: IOUtils is available in the Apache Commons IO library
You need to read the contents of "street.html" into a string to be able to send it with the content type "text/html".
You can try with the apache commons mail api
http://commons.apache.org/proper/commons-email/apidocs/org/apache/commons/mail/HtmlEmail.html
MimeMessage.setText() method sets a default mime type of text/plain.
But i guess you need text/html. This can be done using MimeMessage.setContent().
You can make use of this code on java side.
message.setContent(someHtmlMessage, "text/html; charset=utf-8");
You Need to read the content of local file using one of DataHandler impementation. Need to use overloaded method in MiMeMessage Class API which will accept DataHandler object itself.
MiMeMessage.SetContent(Object, type);
Refer to the API link and google for few samples of usage of method will give the required sloution.
you need to change only
String mess=""// it contains html code
message.setContent(mess,"text/html");
Transport.send(message);
it will work

Updating status with picture via email. (JavaMail)

I'm writing a standalone application in Processing and I need to publish sketch screenshots on FB page timeline via JavaMail.
So I wrote this:
void sendMail() {
String host="smtp.gmail.com";
Properties props=new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable","true");
Session session = Session.getDefaultInstance(props, new Auth());
try
{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("xxxxx#gmail.com", "xxxxx"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("xxxxxxxxxx#m.facebook.com", false));
message.setSubject("ok");
BodyPart mbp = new MimeBodyPart();
DataSource fds = new FileDataSource(file);
mbp.setDataHandler(new DataHandler(fds));
mbp.setFileName("screen.png");
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
message.setContent(mp);
message.setSentDate(new Date());
Transport.send(message);
println("Mail sent!");
}
catch(Exception e)
{
println(e);
}
}
Now, when I write down my gmail e-mail as recipient - method works perfectly (I receive only subject and attached photo), but when I use my FB page e-mail - only subject appears in my timeline, no photo.
I've done the same thing with PHP before and it worked. Maybe I have missed something?
Thank You in advance!:)
Well, I've looked on the content of the original message and noticed this:
Content-Type: application/octet-stream; name=screen.png
So I just added a third line to my code:
MimeBodyPart mbp = new MimeBodyPart();
mbp.attachFile(new File(file));
mbp.setHeader("Content-Type", "image/png");
Then I got:
Content-Type: image/png
and now everything works perfectly!:)
You're creating a multipart message with exactly one part and that one part isn't a text part, it's an image part. While that's perfectly legal according to the MIME spec, it's "unusual", and perhaps Facebook email isn't prepared to handle such a message.
When you did the same thing with PHP, did you create a message with the same structure?
Try NOT creating a multipart message. Instead, just set the image as the content of the message itself.
Also, try creating a multipart message with a first part that's plain text and a second part that's the image.

Categories