Attach file in java mail
Here is an example of how to attach a file to a Java Mail message:
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
public class SendMailWithAttachment {
public static void main(String[] args) {
// Set up the mail server
String host = "your.mail.server";
String user = "your.mail.username";
String password = "your.mail.password";
// Create a new mail session
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", 25);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
// Create a new message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));
msg.setSubject("Test email with attachment");
// Create a new attachment
File file = new File("path/to/your/file.txt");
MimeBodyPart attachment = new MimeBodyPart();
attachment.setFileName(file.getName());
attachment.setContent(file, "text/plain");
// Add the attachment to the message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(attachment);
msg.setContent(multipart);
// Send the message
Transport.send(msg);
}
}
In this example, we create a new MimeBodyPart
object and set its fileName
property to the name of the file we want to attach. We then set the content
property to the file itself, using the File
object as the content.
We then create a new Multipart
object and add the attachment to it using the addBodyPart
method. Finally, we set the content
property of the message to the Multipart
object, which will include the attachment.
Note that you'll need to replace the placeholders (your.mail.server
, your.mail.username
, your.mail.password
, [email protected]
, [email protected]
, and path/to/your/file.txt
) with the actual values for your mail server and file.
Also, make sure to handle exceptions properly, as sending email can fail for various reasons.