Java - Change the name of email attachment using javax.mail library - java

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());

Related

mailing an imageview without saving it in java

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)

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.

How do I add a filename to images attached to emails using javax.mail.jar

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

Sending EMail with Attachment with Java

i have the following code to send an email with attachment. The problem is, that the attachment, which is a simple text file, is empty. But the file isn't.
Just in the email it is. The text is showing correctly. No error codes.
private void emailSenden() throws MessagingException, FileNotFoundException, IOException {
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
Authenticator auth = new SMTPAuthenticator();
Session mailSession = Session.getDefaultInstance(props, auth);
MimeMessage msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress("xyz#xxx.de", "Muster AG"));
msg.setRecipients(Message.RecipientType.TO, "abc#aaa.de");
msg.setSubject("Update erfolgreich.");
msg.setSentDate(new Date());
try {
Multipart mp = new MimeMultipart();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("Update erfolgreich");
mp.addBodyPart(textPart);
MimeBodyPart attachFilePart = new MimeBodyPart();
attachFilePart.attachFile(new File("C:" + File.separator + "log" + File.separator + "logDatei.txt"));
mp.addBodyPart(attachFilePart);
msg.setContent(mp);
msg.saveChanges();
Transport.send(msg);
System.out.println("Email gesendet");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
try this
attachFilePart = new MimeBodyPart();
String filename = "c:\log\logDatei.txt";
DataSource source = new FileDataSource(filename);
attachFilePart .setDataHandler(new DataHandler(source));
attachFilePart .setFileName(filename);
multipart.addBodyPart(attachFilePart );

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.

Categories