1 原始
过去发邮件到 SMTP 专用的25端口很简单,因为没有安全校验
//打开到主机的套接字
Socket s = new Socket("mail.server.com",25);
PrintWriter out = new PrintWriter(s.getOutputStream(), "UTF-8");
//打印发送信息
out.print("HELO sending host\r\n");
out.print("MAIL FROM: sender e-mail address\r\n");
out.print("RCPT TO: recipient e-mail address\r\n");
out.print("DATA\r\n");
out.print("Subject: subject\r\n");
out.print("\r\n");//blank line
out.print("mail message...\r\n");
out.print(".\r\n");
out.print("QUIT\r\n");
如今许多服务器都内置了检查功能,并且只接受授信请求。其中人工实现认证非常冗长,通常使用 JavaMail
2 JavaMail
JavaMail 是实现邮件发送和接收功能,支持一些常用的邮件协议,无须考虑邮件的底层实现细节。
2.1 Maven 引入
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
2.2 简单的纯文本邮件
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.host", "smtp.sina.com");
Session session = Session.getInstance(props);
session.setDebug(true);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(MimeMessage.RecipientType.TO,new InternetAddress(to));
msg.setSubject("邮件主题","UTF-8");
msg.setContent("简单的纯文本邮件!", "text/html;charset=UTF-8");
msg.setSentDate(new Date());
Transport transport = session.getTransport();
transport.connect(senderAccount, senderPassword);
transport.sendMessage(msg,msg.getAllRecipients());
//发送给指定的人
//transport.sendMessage(msg, new Address[]{new InternetAddress("[email protected]")});
transport.close();