How to send attachment in mail using java
To send an email with an attachment using Java, you can use the JavaMail API. Here's a step-by-step guide:
Step 1: Add the JavaMail API to your project
You can add the JavaMail API to your project using Maven or Gradle. Here's an example of how to add it using Maven:
<dependencies>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
</dependencies>
Step 2: Create a JavaMail session
Create a JavaMail session using the Session
class:
import javax.mail.Session;
import javax.mail.PasswordAuthentication;
public class EmailSender {
public static void main(String[] args) {
// Create a JavaMail session
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");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email-username", "your-email-password");
}
});
}
}
Step 3: Create a MimeMessage
Create a MimeMessage
object to represent the email:
import javax.mail.internet.MimeMessage;
public class EmailSender {
//...
public static void sendEmail(String toAddress, String subject, String body, File attachment) throws Exception {
// Create a MimeMessage
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email-username"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
message.setSubject(subject);
message.setText(body);
// Add the attachment
message.setFileName(attachment.getName());
message.setFileNameEncoding("UTF-8");
message.setDataHandler(new DataHandler(new ByteArrayDataSource(attachment, "application/octet-stream")));
// Send the email
Transport.send(message);
}
}
Step 4: Send the email
Send the email using the Transport
class:
public class EmailSender {
//...
public static void main(String[] args) {
//...
// Send the email
sendEmail("[email protected]", "Test Email", "Hello, this is a test email!", new File("path/to/attachment.txt"));
}
}
Step 5: Handle exceptions
Make sure to handle any exceptions that may occur during the email sending process:
public class EmailSender {
//...
public static void sendEmail(String toAddress, String subject, String body, File attachment) throws Exception {
//...
try {
Transport.send(message);
} catch (MessagingException e) {
throw new Exception("Error sending email: " + e.getMessage());
}
}
}
That's it! With these steps, you should be able to send an email with an attachment using Java.
Here's the complete code:
import javax.mail.*;
import javax.mail.internet.*;
import java.io.*;
import java.util.*;
public class EmailSender {
public static void main(String[] args) {
// Create a JavaMail session
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");
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("your-email-username", "your-email-password");
}
});
// Send the email
sendEmail("[email protected]", "Test Email", "Hello, this is a test email!", new File("path/to/attachment.txt"));
}
public static void sendEmail(String toAddress, String subject, String body, File attachment) throws Exception {
// Create a MimeMessage
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("your-email-username"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
message.setSubject(subject);
message.setText(body);
// Add the attachment
message.setFileName(attachment.getName());
message.setFileNameEncoding("UTF-8");
message.setDataHandler(new DataHandler(new ByteArrayDataSource(attachment, "application/octet-stream")));
// Send the email
try {
Transport.send(message);
} catch (MessagingException e) {
throw new Exception("Error sending email: " + e.getMessage());
}
}
}
class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
this.data = data;
this.type = type;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
@Override
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not supported");
}
@Override
public String getContentType() {
return type;
}
@Override
public String getName() {
return "attachment";
}
}
Make sure to replace the placeholders (your-smtp-host
, your-smtp-port
, your-email-username
, your-email-password
, and path/to/attachment.txt
) with your actual email settings and attachment path.