共計 1339 個字符,預計需要花費 4 分鐘才能閱讀完成。
Java 實現發送郵件的代碼可以使用 JavaMail 庫來完成。以下是一個簡單的示例代碼:
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
public class SendEmail {public static void main(String[] args) {
// 發送方郵箱地址
String fromEmail = "your_email@example.com";
// 發送方郵箱密碼或授權碼
String password = "your_password";
// 接收方郵箱地址
String toEmail = "recipient_email@example.com";
// 配置 SMTP服務器 的屬性
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// 創建 Session 對象
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(fromEmail, password);
}
});
try {
// 創建 MimeMessage 對象
MimeMessage message = new MimeMessage(session);
// 設置發件人
message.setFrom(new InternetAddress(fromEmail));
// 設置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
// 設置郵件主題
message.setSubject("Test Email");
// 設置郵件內容
message.setText("This is a test email.");
// 發送郵件
Transport.send(message);
System.out.println("Email sent successfully!");
} catch (MessagingException e) {e.printStackTrace();
}
}
}
請注意,你需要將代碼中的 ”your_email@example.com”,”your_password”,”smtp.example.com”,”recipient_email@example.com” 替換為你自己的郵箱地址、密碼、SMTP 服務器地址和接收方郵箱地址。
丸趣 TV 網 – 提供最優質的資源集合!
正文完