import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { public static void main(String[] args) { String from = "sender@example.com"; String password = "password"; String to = "recipient@example.com"; String subject = "Hello from JavaMail API"; String body = "This is the message body."; Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.example.com"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); message.setText(body); Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { e.printStackTrace(); } } }


上一篇:
下一篇:
切换中文