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);
Related
In Javamail Attachment is not displaying
I tried to send a mail with attachment
It sending and received But in received mail attachment is not displaying not display
attachment is blank and
Here the code is:
#Bean
public JavaMailSenderImpl mailSender() {
JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
javaMailSender.setProtocol("smtp");
javaMailSender.setHost("smtp.gmail.com");
javaMailSender.setPort(587);
javaMailSender.setUsername("*******#gmail.com");
javaMailSender.setPassword("*********");
Properties props = ((JavaMailSenderImpl) javaMailSender).getJavaMailProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.debug", "true");
props.put("mail.mime.multipart.allowempty", "true");
javaMailSender.setJavaMailProperties(props);
return javaMailSender;
}
{
message.setSubject(mailServiceDTO.getSubject());
message.setText(mailServiceDTO.getSubject(), "text/html");
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailServiceDTO.getSubject(), "text/html");
for (EmailAttachment attachment : mailServiceDTO.getAttachments()) {
message.addAttachment(attachment.getAttachmentName(), new ByteArrayResource(attachment.getAttachmentContent().getBytes()));
}
Multipart mp = new MimeMultipart();
mp.addBodyPart(messageBodyPart);
mimeMessage.setContent(mp);
javaMailSender.send(mimeMessage);
}
you can use MimeMessageHelper in spring mail.
Example
MimeMessage msg = javaMailSender.createMimeMessage();
MimeMessageHelper mailMessage = null;
List<PathSource> pathSourceList = request.getMailAttachList();
if (pathSourceList != null && pathSourceList.size() > 0)
mailMessage = new MimeMessageHelper(msg, true);
else
mailMessage = new MimeMessageHelper(msg, false);
// ....
if (pathSourceList != null && pathSourceList.size() > 0) {
for (PathSource filepath : pathSourceList) {
ByteArrayResource stream = new ByteArrayResource(DatatypeConverter.parseBase64Binary(
filepath.getData()));
mailMessage.addAttachment(filepath.getFileName(), stream);
}
}
try {
javaMailSender.send(mailMessage.getMimeMessage());
} catch (Exception ex) {
log.error("server info {}", serverModel.toString());
throw ex;
}
Add Multiple attachments..
public static void main(String[] args) {
final String fromEmail = ""; // requires valid gmail id
final String password = "";// correct password for gmail id
final String toEmail = ""; // can be any
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); // SMTP Host
props.put("mail.smtp.port", "587"); // TLS Port
props.put("mail.smtp.auth", "true"); // enable authentication
props.put("mail.smtp.starttls.enable", "true"); // enable STARTTLS
Authenticator auth = new Authenticator() {
// override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
sendAttachmentEmail(session,fromEmail, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");
}
public static void sendAttachmentEmail(Session session,String fromEmail, String toEmail, String subject, String body){
try{
MimeMessage msg = new MimeMessage(session);
msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
msg.addHeader("format", "flowed");
msg.addHeader("Content-Transfer-Encoding", "8bit");
msg.setFrom(new InternetAddress(fromEmail));
msg.setReplyTo(InternetAddress.parse(toEmail, false));
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
// Create the message body part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText(body);
// Create a multipart message for attachment
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
String filename1 = "C:\\TraingWorkspace\\Training\\logs\\DailyLog.zip";
addAttachment(multipart, filename1);
String filename2 = "C:\\TraingWorkspace\\Training\\logs\\DailyLog.log";
addAttachment(multipart, filename2);
// Send the complete message parts
msg.setContent(multipart);
// Send message
Transport.send(msg);
System.out.println("EMail Sent Successfully with attachment!!");
}catch (MessagingException e) {
e.printStackTrace();
}
}
private static void addAttachment(Multipart multipart, String filename) throws MessagingException
{
DataSource source = new FileDataSource(filename);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
}
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
I would like to create a MimeMessage which must have two parts as shown below picture (Part_0 and Part_2)
I'm trying to use below code to generated s/mime
public static void main(String[] a) throws Exception {
// create some properties and get the default Session
Properties props = new Properties();
// props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
// session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
try {
msg.addHeader("Content-Type", "multipart/signed; protocol=\"application/pkcs7-signature;");
msg.setFrom(new InternetAddress(FROM_EMAIL));
InternetAddress[] address = {new InternetAddress(
TO_EMAIL)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test Subject");
msg.setSentDate(new Date());
// create and fill the first message part
MimeBodyPart bodyPart1 = new MimeBodyPart();
bodyPart1.setHeader("Content-Type", "text/html; charset=utf-8");
bodyPart1.setContent("<b>Hello World</b>", "text/html");
Multipart multiPart = new MimeMultipart();
multiPart.addBodyPart(bodyPart1, 0);
try (OutputStream str = Files.newOutputStream(Paths
.get(UNSIGNED_MIME))) {
bodyPart1.writeTo(str);
}
signMime();
MimeBodyPart attachPart = new MimeBodyPart();
String filename = SIGNED_VALUE;
DataSource source = new FileDataSource(filename);
attachPart.setDataHandler(new DataHandler(source));
attachPart.setFileName("smime.p7s");
attachPart.addHeader("Content-Type", "application/pkcs7-signature; name=smime.p7s;");
attachPart.addHeader("Content-Transfer-Encoding", "base64");
attachPart.addHeader("Content-Description", "S/MIME Cryptographic Signature");
multiPart.addBodyPart(attachPart);
msg.setContent(multiPart, "multipart/signed; protocol=\"application/pkcs7-signature\"; ");
msg.saveChanges();
try (OutputStream str = Files.newOutputStream(Paths
.get(SIGNED_MIME))) {
msg.writeTo(str);
}
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
}
}
I used two MimeBodyPart however I always got one Part_0 and generated eml file shown below.
I haven't tried to compile it, but what you want is something like this. The inner multipart is a body part of the outer multipart.
msg.setFrom(new InternetAddress(FROM_EMAIL));
InternetAddress[] address = {new InternetAddress(
TO_EMAIL)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject("Test Subject");
msg.setSentDate(new Date());
MultipartSigned multiSigned = new MultipartSigned();
// create and fill the first message part
MimeBodyPart bodyPart1 = new MimeBodyPart();
bodyPart1.setText("<b>Hello World</b>", "utf-8", "html");
Multipart multiPart = new MimeMultipart();
multiPart.addBodyPart(bodyPart1);
// add other content to the inner multipart here
MimeBodyPart body = new MimeBodyPart();
body.setContent(multiPart);
multiSigned.addBodyPart(body);
try (OutputStream str = Files.newOutputStream(Paths
.get(UNSIGNED_MIME))) {
body.writeTo(str);
}
signMime();
MimeBodyPart attachPart = new MimeBodyPart();
String filename = SIGNED_VALUE;
attachPart.attachFile(filename,
"application/pkcs7-signature; name=smime.p7s", "base64");
attachPart.setFileName("smime.p7s");
attachPart.addHeader("Content-Description",
"S/MIME Cryptographic Signature");
multiSigned.addBodyPart(attachPart);
msg.setContent(multiSigned);
msg.saveChanges();
And you'll need this:
public class MultipartSigned extends MimeMultipart {
public MultipartSigned() {
super("signed");
ContentType ct = new ContentType(contentType);
ct.setParameter("protocol", "application/pkcs7-signature");
contentType = ct.toString();
}
}
You could make this much cleaner by moving more of the functionality into the MultipartSigned class.
What you are looking for is Spring Mime Helper.
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.
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();