网易提供了免费的 SMTP / POP3服务,可用于编程测试,详情见 什么是POP3、SMTP和IMAP?
只需要拥有一个网易邮箱账号,并开启该账号的 SMTP / POP3 功能,便可以通过程序发送邮件到 SMTP 服务器,并有 SMTP 服务器发送到收件人邮箱;或者通过 POP3 获取网易邮箱上本人的邮件。
下面是一个简单的案例,利用 JavaMail 发送邮件到网易的 SMTP 服务器,随后便可以在收件人信箱找到程序发送邮件。
package mail; import java.util.Properties; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendEmail { public static void main(){ String to = "[email protected]"; String from = "[email protected]"; final String username = "[email protected]"; final String password = "password"; String host = "smtp.163.com"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.port", "25"); Session session = Session.getInstance(props, new javax.mail.Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject("ssssssss222"); message.setText("ttttttttttttttttt222"); Transport.send(message); System.out.println("Sent "); }catch(Exception e){ System.out.println(e); for (StackTraceElement s : e.getStackTrace()){ System.out.println(s); } } } }
参考资料
avaMail API - Sending Simple Email
时间: 2024-10-10 11:01:03