Sending Email with Java..Attachment code not working? - java

I have just tried to send an email through java code. Actually it works fine with no errors at all.But when i recieve email it does not contain attachment which according to the code should be there("try.txt").
I have no idea at all about JavaMail i just gone through this code and tried this
Code Here
import java.util.*;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "******"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "*******"; // GMail password
private static String RECIPIENT = "*******";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Find An Attachment";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
//session.setDebug(true);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
//attachment
messageBodyPart = new MimeBodyPart();
String filename = "C:/try.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
Something special need to be added for an attachment to be sent properly ?
Please guide me.
Thanks in advance

Remove this line from your code
message.setText(body);
setText() internally calls setContent() function. So if you call setText() function after you setContent, it basically over-rides the content you initially set.
See this for more Information.

Try this:
MimeBodyPart mimeBody = new MimeBodyPart();
mimeBody.attachFile(file);
MimeMultipart mimeMulti = new MimeMultipart();
mimeMulti.addBodyPart(mimeBody);
msg.setContent(mimeMulti);

I faced similar challenges sending email with attachments programatically. I used Apache Commons Email like this:
public static final String ATTACHMENT_PATH = "/opt/testfile/example_4mb_file.mp4";
// Create the attachment
File attachFile = new File(ATTACHMENT_PATH);
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(attachFile.getAbsolutePath());
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription(attachFile.getName());
attachment.setName(attachFile.getName());
// Create the email message
MultiPartEmail email = new MultiPartEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator(
EMAIL_USERNAME,
EMAIL_PASSWORD));
email.setSSLOnConnect(true);
email.addTo(EMAIL_RECEIVER);
email.setFrom(EMAIL_SENDER, EMAIL_SUBJECT);
email.setSubject("TestMail id " + this.uniqueId);
email.setMsg("This is a test attachment mail ... :-)");
// add the attachment
email.attach(attachment);
// send the email
email.send();

Related

JavaMail mail and attachment

I am trying to send an email with html text and attachment using JavaMail.
However, I can only seem to make one work at a time, either it sends the html text or sends the attachment, but not both, I cant figure out how to make both.
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");
final String username = "email#gmail.com";
final String password = "**********************";
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("email#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("email to send"));
message.setSubject("Testing Subject");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
// Attachment
String file = "/Users/user/Desktop/file.rtf";
String fileName = "file.rtf";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent("<h1>HTML Text</h1>",
"text/html");
//HTML Text
message.setContent(multipart); //attachment
//Send
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e)
{
e.printStackTrace();
throw new RuntimeException(e);
}
Here is my working code for a recent project I worked on. Hope it helps!
String from = "JohnDoe#gmail.com";
String pass = "***********";
String[] to = { "JohnDoe#gmail.com" }; // list of recipient email addresses
String subject = "Subject Line";
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "send.jpeg";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.setSubject(subject);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
You're calling message.setContent twice. The second call overrides the first call, replacing the content.
See the JavaMail sample program sendfile.java for a complete working example.

JavaMail API Error (javax.mail.NoSuchProviderException: invalid provider)

I'm trying to create a program using the JavaMail API, however, I keep getting the following error message.
javax.mail.NoSuchProviderException: invalid provider
at javax.mail.Session.getTransport(Session.java:738)
at javax.mail.Session.getTransport(Session.java:682)
at javax.mail.Session.getTransport(Session.java:662)
at EmailAutoResponder2.main(EmailAutoResponder2.java:56)
I was not able to solve it by reading online, as all of their solutions still gave me the same message.
Here is the Java code:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailAutoResponder2 {
public static void main(String[] args) {
String to = "username#videotron.ca";
String from = "username#videotron.ca";
Properties properties = System.getProperties();
properties.setProperty("mail.store.protocol", "imaps");
Session session1 = Session.getInstance(properties);
//If email received by specific user, send particular response.
Properties props = new Properties();
props.put("mail.imap.auth", "true");
props.put("mail.imap.starttls.enable", "true");
props.put("mail.imap.host", "imap.videotron.ca");
props.put("mail.imap.port", "143");
Session session2 = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username#videotron.ca", "password");
}
});
try {
Store store = session2.getStore("imap");
store.connect("imap.videotron.ca", "username#videotron.ca", "password");
Folder fldr = store.getFolder("Inbox");
fldr.open(Folder.READ_ONLY);
Message msgs[] = fldr.getMessages();
for(int i = 0; i < msgs.length; i++){
System.out.println(InternetAddress.toString(msgs[i].getFrom()));
if (InternetAddress.toString(msgs[i].getFrom()).startsWith("Name")){
MimeMessage message = new MimeMessage(session1);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Subject");
message.setText("Message");
String protocol = "imap";
props.put("mail." + protocol + ".auth", "true");
Transport t = session2.getTransport("imap");
try {
t.connect("username#videotron.ca", "password");
t.sendMessage(message, message.getAllRecipients());
}
finally {
t.close();
}
}
}
}
catch(MessagingException mex){
mex.printStackTrace();
}
catch(Exception exc) {
}
}
}
Thank you!
You're connecting to localhost to send the message. Do you have a mail server running on your local machine? Probably not. You need to set the mail.smtp.host property. You may also need to supply a username and password for your mail server; see the JavaMail FAQ.
The following code may solve your problem
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Email {
private static String USER_NAME = "username"; // GMail user name (just the part before "#gmail.com")
private static String PASSWORD = "password"; // GMail password
private static String RECIPIENT = "xxxxx#gmail.com";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "hi ....,!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.trust", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}

sending mail with attachment AND a message

why does it not work to send a message and an attachment
when i use this code below it will send the mail and attachment but not the message.
some one who knows why or how to ?
Working code, I have used Java Mail 1.4.7 jar.
import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
public class MailProjectClass {
public static void main(String[] args) {
final String username = "your.mail.id#gmail.com";
final String password = "your.password";
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");
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.mail.id#gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to.mail.id#gmail.com"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
String file = "path of file to be attached";
String fileName = "attachmentName";
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
You need to add email body as a separate multi part
String body="Email body template";
MimeBodyPart mailBody = new MimeBodyPart();
mailBody.setText(body);
multipart.addBodyPart(mailBody);
Considering the fact that you missed the ; here String fileName = "attachmentName" as typo.
But other than that your code works perfectly fine.

How to send an email whose attachment has an extension on delivery

I'm trying to send an email with an attachment. The whole thing works fine, except for the part that the attachment sent sends the attached file with no extension.
For example, sending File.rar will receive file
This is how I'm doing it:
public class EmailSender {
public static void main(String[] args) {
String TO = "Receiver#yahoo.com";
String host = "smtp.gmail.com";
String port = "465";
String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties mailConfig = new Properties();
mailConfig.put("mail.smtp.host", host);
mailConfig.put("mail.smtp.socketFactory.port", port);
mailConfig.put("mail.smtp.socketFactory.class", SSL_FACTORY);
mailConfig.put("mail.smtp.auth", "true");
mailConfig.put("mail.smtp.port", port);
Session session = Session.getDefaultInstance(mailConfig,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("Username", "Password");
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("from#gmail.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
message.setSubject("Email with Attachment SUBJECT");
BodyPart messageBodyTxt = new MimeBodyPart();
messageBodyTxt.setText("Email with Attachment BODY");
MimeBodyPart messageBodyAttachment = new MimeBodyPart();
String filePath = "D:\\Unlocker1.9.2.rar";
DataSource source = new FileDataSource(filePath);
messageBodyAttachment.setDataHandler(new DataHandler(source));
messageBodyAttachment.setFileName("Unlocker1.9.2" + ".rar");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyTxt);
multipart.addBodyPart(messageBodyAttachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Email sent successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
Using the advice from the comment, the proper method would be setDisposition and you would set it for the MimeBodyPart in question. Therefore, with the code above, one would do:
messageBodyAttachment.setDisposition(javax.mail.Part.ATTACHMENT);

Sending an Email Using Java

try{
Properties props = new Properties();
props.put("mail.smtp.host", "ipc-smtp.bits-pilani.ac.in");
Session sess = Session.getInstance(props, null);
sess.setDebug(true);
Message msg = new MimeMessage(sess);
InternetAddress addressFrom = new InternetAddress("mymail#gmail.com");
msg.setFrom(addressFrom);
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("mymail#gmail.com"));
msg.addHeader("MyHeaderName", "myHeaderValue");
msg.setSubject("Test");
msg.setContent("Yippe", "text/plain");
Transport.send(msg);
}catch(Exception exp){
exp.printStackTrace();
}
The error is javax.mail.MessagingException: 554 The mail was blocked due to zen-spamhaus RBL action
This is my college's smtp server.
I would inform your college's IT dept and they should be able to handle the issue. Although since it appears they left an open relay, maybe not.
import javax.mail.*;
import javax.mail.internet.*;
.....
public static void postMail(String[] recipients, String subject, String message, String from) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", Util.getProperty("smtpHost"));
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
//msg.addHeader("MyHeaderName", "myHeaderValue");
msg.setSubject(subject);
msg.setContent(message, "text/html");
Transport.send(msg);
}

Categories