共計(jì) 2256 個(gè)字符,預(yù)計(jì)需要花費(fèi) 6 分鐘才能閱讀完成。
在 Java 中發(fā)送帶附件的郵件可以使用 JavaMail API 來實(shí)現(xiàn)。以下是一個(gè)示例代碼:
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) {// 發(fā)件人郵箱和密碼
final String username = "your_email@example.com";
final String password = "your_password";
// 發(fā)件人郵箱的 SMTP 服務(wù)器地址
final String smtpHost = "smtp.example.com";
// 收件人郵箱
String toEmail = "recipient@example.com";
// 創(chuàng)建郵件會(huì)話
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 {// 創(chuàng)建郵件消息
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
message.setSubject("JavaMail Attachment Example");
// 創(chuàng)建郵件內(nèi)容
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is a sample email with attachment.");
// 附件文件路徑
String attachmentPath = "/path/to/attachment.txt";
// 創(chuàng)建附件
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachmentPath);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(source.getName());
// 將內(nèi)容和附件添加到郵件中
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachmentBodyPart);
message.setContent(multipart);
// 發(fā)送郵件
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (MessagingException e) {e.printStackTrace();
}
}
}
在上述代碼中,你需要替換以下內(nèi)容:
your_email@example.com
:發(fā)件人郵箱your_password
:發(fā)件人郵箱密碼smtp.example.com
:發(fā)件人郵箱的 SMTP 服務(wù)器地址recipient@example.com
:收件人郵箱/path/to/attachment.txt
:附件的文件路徑
確保你已經(jīng)添加了 javax.mail
和activation
依賴,以及正確配置了郵件服務(wù)器信息。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完