How to send a mail with attachment in java
Here is an example of how to send an email with an attachment in Java using the JavaMail API:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
public class SendEmailWithAttachment {
public static void main(String[] args) {
// Set up the email properties
Properties props = new Properties();
props.put("mail.smtp.host", "your-smtp-host");
props.put("mail.smtp.port", "your-smtp-port");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Create a session
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email-username", "your-email-password");
}
});
// Create a message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email-username"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient-email-username"));
message.setSubject("Test Email with Attachment");
// Create a MIME body part for the attachment
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is a test email with an attachment.");
// Create a MIME body part for the attachment
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile("path/to/attachment/file.txt");
// Create a Multipart object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentBodyPart);
// Set the message body
message.setContent(multipart);
// Send the email
Transport.send(message);
}
}
This code sends an email with a text body and a file attachment. You'll need to replace the placeholders with your own values:
your-smtp-host
: the hostname of your SMTP serveryour-smtp-port
: the port number of your SMTP serveryour-email-username
: your email usernameyour-email-password
: your email passwordrecipient-email-username
: the email address of the recipientpath/to/attachment/file.txt
: the path to the file you want to attach
You'll also need to add the JavaMail API to your project. You can do this by adding the following dependency to your pom.xml
file (if you're using Maven):
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
Or by downloading the JavaMail API JAR file and adding it to your project's classpath.
Note that this is just a basic example, and you may need to add additional error handling and configuration depending on your specific use case.