在Java中發送帶附件的郵件可以使用JavaMail API來實現。以下是一個示例代碼:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
public class EmailSender {
public static void main(String[] args) {
// 發件人郵箱和密碼
final String username = "your_email@example.com";
final String password = "your_password";
// 發件人郵箱的 SMTP 服務器地址
final String smtpHost = "smtp.example.com";
// 收件人郵箱
String toEmail = "recipient@example.com";
// 創建郵件會話
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new 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(toEmail));
message.setSubject("JavaMail Attachment Example");
// 創建郵件內容
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is a sample email with attachment.");
// 附件文件路徑
String attachmentPath = "/path/to/attachment.txt";
// 創建附件
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentPath);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(source.getName());
// 將內容和附件添加到郵件中
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentBodyPart);
message.setContent(multipart);
// 發送郵件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
在上述代碼中,你需要替換以下內容:
your_email@example.com
:發件人郵箱your_password
:發件人郵箱密碼smtp.example.com
:發件人郵箱的 SMTP 服務器地址recipient@example.com
:收件人郵箱/path/to/attachment.txt
:附件的文件路徑確保你已經添加了javax.mail
和activation
依賴,以及正確配置了郵件服務器信息。