Error when sending Mail and attachment in Java - 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.

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.

Error when sending email via Java Mail API?

I got following error when trying to send email via Java Mail API? What does this error mean?
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
javax.mail.MessagingException: Exception reading response;
nested exception is:
java.net.SocketTimeoutException: Read timed out
at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:2210)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1950)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
Here is my code, i set all parameters (from, to , subjects and attachments)
public static void send(MailUtil mailUtil) throws MessagingException {
MimeMessage message = new MimeMessage(session);
if (props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_SENDER) != null) {
message.setFrom(new InternetAddress(props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_SENDER)));
} else {
message.setFrom(new InternetAddress(mailUtil.getFrom()));
}
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(mailUtil.getTo()));
if (mailUtil.getBcc() != null && mailUtil.getBcc().trim().length() > 0) {
message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(mailUtil.getBcc()));
} else {
message.setRecipients(Message.RecipientType.BCC,InternetAddress.parse(""));
}
message.setSubject(mailUtil.getSubject(), "UTF-8");
// Check for files list and attach them.
if (mailUtil.attachmentFiles != null && mailUtil.attachmentFiles.size() > 0) {
Multipart multipart = new MimeMultipart();
// Set content.
BodyPart messageBodyPart =new MimeBodyPart();
messageBodyPart.setContent(mailUtil.getContent(), "text/plain; charset=utf-8");
multipart.addBodyPart(messageBodyPart);
// Attach files.
for (File file : mailUtil.attachmentFiles) {
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
} else {
//message.setContent("<h1>Hello world</h1>", "text/html");
message.setContent(mailUtil.getContent(), "text/html; charset=UTF-8");
}
Transport.send(message);
}
I just think is there any problem with my paramters?
Belows is my configuration
mail.smtp.port=465
mail.smtp.starttls.enable=true
mail.smtp.auth=true
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.timeout=25000
mail.smtp.host=smtp.gmail.com
mail.username = username#gmail.com
mail.password = mypassword
mail.sender = sender#gmail.com
mail.receiver = receiver#gmail.com
mail.subject = mysubject
I am using google mail server! I dont' think there is problem there!
Belows is session initiation
final String userName = props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_USERNAME);
final String passWord = props.getProperty(IConstants.DL_MAIL_CONFIGURATION.MAIL_PASSWORD);
session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName,
passWord);
}
});
I believe it absolutely relates to server configuration.
When I change the port configuration from 465 to 587, it solves my problem!
Anyway, thank you guy for your help!
Your code and configuration contain many of these common mistakes. In particular, the use of Session.getDefaultInstance may mean you're not using the configuration you think you're using. If fixing that doesn't solve your problem, post the JavaMail session debug output.
I'm not sure why you use a "mail" object to setup the connection properties, instead try this, it should work, I've tested myself:
private Properties props;
props = System.getProperties();
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");
session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
message.setFrom(new InternetAddress("YOUR EMAIL ADDRESS HERE"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("RECEIVER EMAIL ADDRESS HERE"));
message.setSubject("SUBJECT");
message.setText("THE EMAIL TEXT");
Transport.send(message);
} catch (MessagingException e) {e.printStackTrace();}
}

Issue attaching zip file in javamail

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)

how to attach generated pdf file mail in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Some body please tell me about how to attach available pdf file to mail.
I am use mail.jar and activation.jar for sending a mail.
I can send mail but I dont know how to send pdf file with attachment.
so please suggest me about that
thank you.
I just try
String filename = "file.pdf";
Multipart multipart1 = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart1.addBodyPart(messageBodyPart);
But still it not get data, it empty attached.
Send E-Mail with Attachment using JavaMail :
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
class SendAttachment
{
public static void main(String [] args)
{
String to="ABC#gmail.com";//change accordingly
final String user="ABC#XYZ.com";//change accordingly
final String password="xxxxx";//change accordingly
//1) get the session object
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", "mail.javatpoint.com");
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password); } });
//2) compose message
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
message.setSubject("Message Aleart");
//3) create MimeBodyPart object and set your message text
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("This is message body");
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "SendAttachment.java";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart );
//7) send message
Transport.send(message);
System.out.println("message sent....");
}catch (MessagingException ex) {ex.printStackTrace();}
}
}
source: http://www.javatpoint.com/example-of-sending-attachment-with-email-using-java-mail-api
Try this:
String SMTP_HOST_NAME = "mail.domain.com";
String SMTP_PORT = "111";
String SMTP_FROM_ADDRESS="xxx#domain.com";
String SMTP_TO_ADDRESS="yyy#domain.com";
String subject="Textmsg";
String fileAttachment = "C:\\filename.pdf";
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.smtp.port", SMTP_PORT );
Session session = Session.getInstance(props,new javax.mail.Authenticator()
{protected javax.mail.PasswordAuthentication
getPasswordAuthentication()
{return new javax.mail.PasswordAuthentication("xxxx#domain.com","password");}});
try{
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(SMTP_FROM_ADDRESS));
// create the message part
MimeBodyPart messageBodyPart =
new MimeBodyPart();
//fill message
messageBodyPart.setText("Test mail one");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source =
new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(
new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(multipart);
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(SMTP_TO_ADDRESS));
msg.setSubject(subject);
// msg.setContent(content, "text/plain");
Transport.send(msg);
System.out.println("success....................................");
}
catch(Exception e){
e.printStackTrace();
}
Source: http://www.coderanch.com/t/586537/java/java/sample-code-java-mail-api
You should create MimeMultipart, MimeBodyPart, FileDataSource and DataHandler as follows:
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String filePath = "<file system path>";
String fileName = "display name"
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
Now, On MimeMessage use setContent method.

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