计算机网络——用smtp实现Email客户端

实验目的

运用各种编程语言实现基于 smtp 协议的 Email 客户端软件。

实验环境

系统:Mac OS X 10.13.1
语言:Java
连接协议:smtp
邮箱主机:smtp.qq.com(qq邮箱)
外部jar文件:javax.mail.jar

实验过程

代码部分

为了完成本次试验的要求,我编写了一个Java代码文件,具体的算法流程如下:

邮箱端配置

为了方便起见,我在这里使用qq邮箱作为我的测试邮箱,但是qq邮箱默认是关闭smtp服务的,所以我们需要先开启smtp协议。

  1. 首先在qq邮箱的个人账户部分找到如下服务的对应位置(此图为开启之后所截,故显示已经开启):
    Alt text
  2. 配合手机操作操作之后,我们可以得到如下的开通反馈,其中返回的授权码极为重要,其关系到代码中transport.connect()方法的执行成功与否:
    Alt text

代码测试

由查阅可得,qq邮箱的服务器如下,且使用端口为465或587:
Alt text
将服务器(smtp.qq.com)、端口(465)、收件人(835381071@qq.com)发件人邮箱(835381071@qq.com)和标题内容设置好之后,通过授权码执行连接,可以debug测试输出如下:
Alt text
Alt text

执行结果

最后为了验证我们的执行结果,打开qq邮箱的收件箱,可以看到如下信息:
Alt text

代码附录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package smpt;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

public class SendmailUtil {
public static void main(String[] args) throws AddressException, MessagingException {
Properties properties = new Properties();
// 使用smtp协议
properties.put("mail.transport.protocol", "smtp");
//qq邮箱的主机名
properties.put("mail.smtp.host", "smtp.qq.com");
//qq邮箱使用465端口
properties.put("mail.smtp.port", 465); // 端口号
//login验证
properties.put("mail.smtp.auth", "true");
//使用ssl安全连接
properties.put("mail.smtp.ssl.enable", "true");
// 设置是否显示debug信息 true 会在控制台显示相关信息
properties.put("mail.debug", "true");
// Session用于收集JavaMail运行过程中的环境信息
Session session = Session.getInstance(properties);
// 获取邮件对象
Message message = new MimeMessage(session);
// 设置发件人邮箱地址
message.setFrom(new InternetAddress("835381071@qq.com"));
// 设置收件人地址
message.setRecipients( RecipientType.TO, new InternetAddress[] { new InternetAddress("835381071@qq.com") });
// 设置邮件标题
message.setSubject("smtp测试邮件");
// 设置邮件内容
message.setText("内容:smtp发送邮件成功!");
// 得到邮差对象
Transport transport = session.getTransport();
// 连接自己的邮箱账户
transport.connect("835381071@qq.com", "sgxclkuvvirtbdfe");
// 发送邮件
transport.sendMessage(message, message.getAllRecipients());
}
}
小手一抖⬇️