在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
依赖,以及正确配置了邮件服务器信息。