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.
Related
Salam,
I have an application that generate time tabling in a grid pane and i could turn the gridpane to image in order to print it but now i want to send that image in email but i can't find a way
I have seen similiar topics but they send image existing in computer by its path but in my case i don't want to save the image i just want to send it directly with java class Image or ImageView
Here is my code
#FXML
void send_mail(ActionEvent event) throws IOException {
final String username = "******#gmail.com";
final String 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");
javax.mail.Session session = javax.mail.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(username));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("*****#yahoo.com"));
message.setSubject("Testing Subject");
message.setText("PFA");
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(image, "IMAGEVIEW");
// String file = "../emploi/"+fileName;
messageBodyPart.setText("Emploi de temps");
//DataSource source = new FileDataSource(file);
// messageBodyPart.setDataHandler(new DataHandler((DataSource) file));
// messageBodyPart.attachFile(file);
messageBodyPart.setFileName("Emploi de temps");
multipart.addBodyPart(messageBodyPart);
MimeBodyPart photoBodyPart = new MimeBodyPart();
photoBodyPart = new MimeBodyPart();
photoBodyPart.setContent(image, "IMAGEVIEW");
multipart.addBodyPart(photoBodyPart);
message.setContent(multipart);
System.out.println("Sending");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
e.printStackTrace();
}
}
but i get this error
javax.mail.internet.ParseException: In Content-Type string ,
expected '/', got null at
javax.mail.internet.ContentType.(ContentType.java:104) at
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1510)
at
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1172)
at
javax.mail.internet.MimeMultipart.updateHeaders(MimeMultipart.java:522)
at
javax.mail.internet.MimeBodyPart.updateHeaders(MimeBodyPart.java:1533)
at
javax.mail.internet.MimeMessage.updateHeaders(MimeMessage.java:2271)
at javax.mail.internet.MimeMessage.saveChanges(MimeMessage.java:2231)
at javax.mail.Transport.send(Transport.java:123)
I'm able to successfully send myself an email with an image, however, the image comes as a file named noname (on gmail, anyway). How can I change the file name of the image I am attaching to the email?
Here is the section of code I am using for sending an email with an image:
public void SendEmail(
String smtp_host_,
String smtp_port_,
String smtp_username_,
String smtp_password_,
String to_,
String subject_,
String body_,
String image_path_) {
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtp_host_);
props.put("mail.smtp.port", smtp_port_);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtp_username_, smtp_password_);
}
});
try {
Message message = new MimeMessage(session);
message.setSubject(subject_);
message.setFrom(new InternetAddress(smtp_username_));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to_));
MimeMultipart multipart = new MimeMultipart("related");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(body_, "text/html");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource(image_path_);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<image>");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport transport = session.getTransport();
transport.connect();
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
}
catch (MessagingException e) {
throw new RuntimeException(e);
}
}
Look at javax.mail.internet.MimeBodyPart.setFileName(String).
You can do it after creating the part:
messageBodyPart = new MimeBodyPart();
((MimeBodyPart) messageBodyPart).setFileName("filename.ext");
See java docs here
Here is my current code. It correctly sends an email with an attachment, but the file name of the attachment sent is the full path to the file on my computer. I want it to show up just as the file name (i.e. "name_of_file.zip" as opposed to "/Users/MyUser/Desktop/name_of_file.zip"). Is there a way to do this?
public void sendMailWithAttachments () {
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); }});
String msgBody = "Body of email";
String fileAttachment = "/Users/MyUser/Desktop/name_of_file.zip";
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("me#email.com"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("person#email.com"));
msg.setSubject("Email Subject!");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(msgBody);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileAttachment);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send(msg);
} catch (AddressException e) {
System.out.println(e);
} catch (MessagingException e) {
System.out.println(e);
}
}
Change:
messageBodyPart.setFileName(fileAttachment);
to:
messageBodyPart.setFileName(new File(fileAttachment).getName());
I have here can send mail with multiple attachment:
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);
Multipart multipart = new MimeMultipart();
// creates body part for the message
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
//set message body
BodyPart msgBodyPart = new MimeBodyPart();
msgBodyPart.setText(body);
multipart.addBodyPart(msgBodyPart);
msgBodyPart = new MimeBodyPart();
//attach file
DataSource source = new FileDataSource(attachFile);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachFile);
multipart.addBodyPart(messageBodyPart);
//attach file 2
source = new FileDataSource(attachFile2);
BodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(attachFile2);
multipart.addBodyPart(messageBodyPart2);
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]);
}
} catch (MessagingException ex) {
ex.printStackTrace();
}
message.setSubject(subject);
message.setContent(multipart);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
But the problem is how can I add multiple attachments? I don't know if i can declare many variable or put it on array. The code can only include 2 attachments what if 5 or any in every send of the email.
Create a simple method called, something like, attachFile, which takes a File, Multipart and MimeBodyPart as parameters...
public void attachFile(File file, Multipart multipart, MimeBodyPart messageBodyPart) {
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
}
Call it as often as you need
File attachFiles[] = ...
if (attachFiles > 0) {
//attach file
attachFile(attachFiles[0], multipart, messageBodyPart);
if (attachFiles > 1) {
for (int index = 1; index < attachFiles.length; index++) {
attachFile(attachFiles[0], multipart, new MimeBodyPart());
}
}
}
as an example
Using Java Mail 1.4 and above makes attaching file more simpler,
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.attachFile(String filePath)
multipart.addBodyPart(messageBodyPart);
Have a look at answer given here
https://stackoverflow.com/a/3177640/772590
Step 1
Create a Datasource
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
Step 2 create method to add attachment
private static void addAttachment(Multipart multipart, String filename)
{
DataSource source = new FileDataSource(filename);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
Step 3 call above method to add attachment
addAttachment(multipart, "file1.txt");
addAttachment(multipart, "file2.txt");
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.