Windows 环境下用 smtp 实现 Email 客户端

Posted on 2023-03-20 17:59  Capterlliar  阅读(676)  评论(0编辑  收藏  举报

计算机网络原理实验二

先来看看smtp协议

具体写的时候不用这么多,先ehlo一下,然后登录,发邮件就可以了。

使用QQ邮箱,搜了搜写出来以下代码:

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Base64;
import java.util.Properties;

public class Client {
    public static String mailServer = "smtp.qq.com";
    public static int port = 25;
    public static String name = "capterlliar";
    public static String account = "401464788@qq.com";
    public static String code = "QWQ";


    public static void main(String[] args){
        try{
            Socket socket = new Socket(mailServer, port);
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            printWriter.println("ehlo "+name);
            printWriter.println("auth login");
            printWriter.println(Base64.getEncoder().encodeToString(account.getBytes("utf-8")));
            printWriter.println(Base64.getEncoder().encodeToString(code.getBytes("utf-8")));
            printWriter.println("mail from:<"+account+">");
            printWriter.println("rcpt to:<"+account+">");

            printWriter.println("DATA");
            printWriter.println("SUBJECT:TEST");
            printWriter.println();
            printWriter.println("An e-mail test.");
            printWriter.println(".");    // 正文结束
            printWriter.println();
            printWriter.println("QUIT");
            printWriter.flush();

            String line;
            while((line=br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
View Code

注意密码不是邮箱密码,要去打开POP3/SMTP服务。

打开方法:设置->账号->开启服务

然后生成一个授权码,用账户和授权码的Base64登录。

点击绿色三角,启动,发现报错:mail from 502 Invalid input from * to newxmesmtplogicsvrszb1-0.qq.com

正常的流程应该是这样的:利用Telnet登录qq邮箱发送邮件——SMTP协议学习_Fossette_lhx的博客-CSDN博客

发现是到了mail from时出错,决定自己下一个Telnet手玩一下。

下载地址

安装完在控制面板那选择启动Telnet客户端,然后打开cmd,像上述那样输入信息。输的时候还没有退格,还要输base64,输错一个字母就得重来,手癌患者无能狂怒。

最后发现手动输入的时候250 OK,感觉是Java往里写的太快了,写完授权码Sleep 2s,好,现在能跑了。

 

 大喜,正好怨种朋友出现,这不得给她发点垃圾邮件。发了1封后: