sending mail with attachment AND a message - java

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.

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)

In Javamail Attachment is not displaying

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

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

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

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

Categories