Javamail example with attachment
Here is an example of using JavaMail to send an email with an attachment:
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
public class SendEmailWithAttachment {
public static void main(String[] args) {
// Set the properties for the email
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", 587);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Create a session
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]", "your-password");
}
});
// Create a message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
message.setSubject("Test email with attachment");
// Create a body for the email
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is a test email with an attachment.");
// Create a multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Add an attachment to the message
File file = new File("path/to/attachment.txt");
DataSource source = new FileDataSource(file);
BodyPart attachment = new MimeBodyPart();
attachment.setDataHandler(new DataHandler(source));
attachment.setFileName(file.getName());
multipart.addBodyPart(attachment);
// Set the message body
message.setContent(multipart);
// Send the email
Transport.send(message);
}
}
This example uses the javax.mail
package to send an email with an attachment. Here's a breakdown of the code:
- We set the properties for the email, including the SMTP host, port, authentication, and startTLS enable.
- We create a session using the
Session
class, passing in the properties and an authenticator that provides the username and password for the email account. - We create a message using the
Message
class, setting the from address, to address, subject, and body. - We create a body part for the email using the
MimeBodyPart
class, setting the text content. - We create a multipart message using the
MimeMultipart
class, adding the body part to it. - We add an attachment to the message using the
MimeBodyPart
class, setting the file name and data source. - We set the message body using the
setContent
method, passing in the multipart message. - We send the email using the
Transport
class.
Note that you'll need to replace the placeholders ([email protected]
, your-password
, [email protected]
, and path/to/attachment.txt
) with your actual email account credentials and attachment file path.