java使用Socket实现SMTP协议发送邮件

 更新时间:2016年05月29日 11:01:34   作者:IamOkay  
这篇文章主要为大家详细介绍了java使用Socket实现SMTP协议发送邮件的相关资料,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java 利用Socket实现SMTP协议发送邮件的具体代码,供大家参考,具体内容如下

package mail;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.commons.codec.binary.Base64;
 
public class Mail {
 
  public static void main(String[] args) throws IOException {
    Mail mail = new Mail();
    mail.setSmtpServer("smtp.qq.com");
    mail.setFromMail("1344364****@qq.com");
    mail.addToMail("105648****@qq.com");
    mail.addToMail("long*****@sina.com");
    mail.setUserName("134364****");
    mail.setPassword("*************");
    mail.setSubject("测试邮件");
    mail.setContent("<h1>你好</h1><br/><img src=\"https://www.baidu.com/img/baidu_jgylogo3.gif?v=39549282.gif\" />");
    mail.setShowLog(true);
    mail.send();
    System.out.println("程序结束");
  }
 
  /** 邮件主题 **/
  private String subject;
  /** 从此地址发出 **/
  private String fromMail;
  /** 用户名 **/
  private String userName;
  /** 登录密码 **/
  private String password;
  /** SMTP 服务器地址 **/
  private String smtpServer;
  /** SMTP 服务器端口(默认:25) **/
  private int smtpPort = 25;
  /** 发送到 toMail 中的所有地址 **/
  private List<String> toMail;
  /** 邮件内容 **/
  private String content;
  /** 是否显示日志 **/
  private boolean showLog;
 
  public void addToMail(String mail) {
    if (toMail == null)
      toMail = new ArrayList<String>();
    toMail.add(mail);
  }
 
  public void send() {
    if (smtpServer == null) {
      throw new RuntimeException("smtpServer 不能为空");
    }
    if (userName == null) {
      throw new RuntimeException("userName 不能为空");
    }
    if (password == null) {
      throw new RuntimeException("password 不能为空");
    }
    if (fromMail == null) {
      throw new RuntimeException("fromMail 不能为空");
    }
    if (toMail == null || toMail.isEmpty()) {
      throw new RuntimeException("toMail 不能为空");
    }
    if (content == null || toMail.isEmpty()) {
      throw new RuntimeException("content 不能为空");
    }
 
    Socket socket = null;
    InputStream in = null;
    OutputStream out = null;
    try {
      socket = new Socket(smtpServer, smtpPort);
      socket.setSoTimeout(3000);
      in = socket.getInputStream();
      out = socket.getOutputStream();
    } catch (IOException e) {
      throw new RuntimeException("连接到 " + smtpServer + ":" + smtpPort + " 失败", e);
    }
 
    BufferedReaderProxy reader = new BufferedReaderProxy(new InputStreamReader(in), showLog);
    PrintWriterProxy writer = new PrintWriterProxy(out, showLog);
 
    reader.showResponse();
    writer.println("HELO " + smtpServer);
    reader.showResponse();
    writer.println("AUTH LOGIN");
    reader.showResponse();
    writer.println(new String(Base64.encodeBase64(userName.getBytes())));
    reader.showResponse();
    writer.println(new String(Base64.encodeBase64(password.getBytes())));
    reader.showResponse();
    writer.println("MAIL FROM:" + fromMail);
    reader.showResponse();
    for (String mail : toMail) {
      writer.println("RCPT TO:" + mail);
      reader.showResponse();
    }
    writer.println("DATA");
    writer.println("Content-Type:text/html");
    if (subject != null) {
      writer.println("Subject:" + subject);
    }
    writer.println("From:" + fromMail);
    writer.print("To:");
    for (String mail : toMail) {
      writer.print(mail + "; ");
    }
    writer.println();
    writer.println();
    writer.println(content);
    writer.println(".");
    reader.showResponse();
    writer.println("QUIT");
    reader.showResponse();
    try {
      socket.close();
    } catch (IOException e) {
      System.err.println("发送邮件完成,关闭 Socket 出错:" + e.getMessage());
    }
  }
 
  public String getSubject() {
    return subject;
  }
 
  public void setSubject(String subject) {
    this.subject = subject;
  }
 
  public String getFromMail() {
    return fromMail;
  }
 
  public void setFromMail(String fromMail) {
    this.fromMail = fromMail;
  }
 
  public String getSmtpServer() {
    return smtpServer;
  }
 
  public void setSmtpServer(String smtpServer) {
    this.smtpServer = smtpServer;
  }
 
  public int getSmtpPort() {
    return smtpPort;
  }
 
  public void setSmtpPort(int smtpPort) {
    this.smtpPort = smtpPort;
  }
 
  public String getContent() {
    return content;
  }
 
  public void setContent(String content) {
    this.content = content;
  }
 
  public List<String> getToMail() {
    return toMail;
  }
 
  public void setToMail(List<String> toMail) {
    this.toMail = toMail;
  }
 
  public String getUserName() {
    return userName;
  }
 
  public void setUserName(String userName) {
    this.userName = userName;
  }
 
  public String getPassword() {
    return password;
  }
 
  public void setPassword(String password) {
    this.password = password;
  }
 
  public boolean getShowLog() {
    return showLog;
  }
 
  public void setShowLog(boolean showLog) {
    this.showLog = showLog;
  }
 
  static class PrintWriterProxy extends PrintWriter {
    private boolean showRequest;
 
    public PrintWriterProxy(OutputStream out, boolean showRequest) {
      super(out, true);
      this.showRequest = showRequest;
    }
 
    @Override
    public void println() {
      if (showRequest)
        System.out.println();
      super.println();
    }
 
    public void print(String s) {
      if (showRequest)
        System.out.print(s);
      super.print(s);
    }
  }
 
  static class BufferedReaderProxy extends BufferedReader {
    private boolean showResponse = true;
 
    public BufferedReaderProxy(Reader in, boolean showResponse) {
      super(in);
      this.showResponse = showResponse;
    }
 
    public void showResponse() {
      try {
        String line = readLine();
        String number = line.substring(0, 3);
        int num = -1;
        try {
          num = Integer.parseInt(number);
        } catch (Exception e) {
        }
        if (num == -1) {
          throw new RuntimeException("响应信息错误 : " + line);
        } else if (num >= 400) {
          throw new RuntimeException("发送邮件失败 : " + line);
        }
        if (showResponse) {
          System.out.println(line);
        }
      } catch (IOException e) {
        System.out.println("获取响应失败");
      }
    }
 
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • SpringBoot中关于static和templates的注意事项以及webjars的配置

    SpringBoot中关于static和templates的注意事项以及webjars的配置

    今天小编就为大家分享一篇关于SpringBoot中关于static和templates的注意事项以及webjars的配置,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • 关于maven项目引入maven库没有的jar处理办法

    关于maven项目引入maven库没有的jar处理办法

    这篇文章主要介绍了关于maven项目引入maven库没有的jar处理办法,在平时开发中,有些jar包是不存在maven中央库中的,那么此时该如何解决才能方便后续处理呢,需要的朋友可以参考下本文
    2023-03-03
  • Java 给PDF签名时添加可信时间戳的方法

    Java 给PDF签名时添加可信时间戳的方法

    这篇文章主要介绍了Java 给PDF签名时添加可信时间戳,关于jar导入的问题,本文给大家带来两种方法,一种是手动导入另一种是maven配置导入,需要的朋友可以参考下
    2021-07-07
  • Springboot整合第三方登录功能的实现示例

    Springboot整合第三方登录功能的实现示例

    本文主要介绍了Springboot整合第三方登录功能的实现示例,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • java使用udp实现简单多人聊天功能

    java使用udp实现简单多人聊天功能

    这篇文章主要为大家详细介绍了java使用udp实现简单多人聊天功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • Java设计模式中代理模式应用详解

    Java设计模式中代理模式应用详解

    代理模式(Proxy Parttern)为一个对象提供一个替身,来控制这个对象的访问,即通过代理对象来访问目标对象。本文将通过示例详细讲解一下这个模式,需要的可以参考一下
    2022-11-11
  • java IP归属地功能实现详解

    java IP归属地功能实现详解

    前一阵子抖音和微博开始陆续上了IP归属地的功能,引起了众多热议,有大批在国外的老铁们开始"原形毕露",被定位到国内来,那么IP归属到底是怎么实现的呢?那么网红们的归属地到底对不对呢
    2022-07-07
  • LoggingEventAsyncDisruptorAppender类执行流程源码解读

    LoggingEventAsyncDisruptorAppender类执行流程源码解读

    这篇文章主要介绍了LoggingEventAsyncDisruptorAppender类执行流程源码解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • SpringBoot3使用​自定义注解+Jackson实现接口数据脱敏的步骤

    SpringBoot3使用​自定义注解+Jackson实现接口数据脱敏的步骤

    本文介绍了一种以优雅的方式实现对接口返回的敏感数据,如手机号、邮箱、身份证等信息的脱敏处理,这种方法也是企业常用方法,话不多说我们一起来看一下吧
    2024-03-03
  • JavaScript中栈和队列应用详情

    JavaScript中栈和队列应用详情

    这篇文章主要介绍了JavaScript中栈和队列应用详情,栈如果用数组模拟的话是类似于一个U形桶状堆栈空间,文章围绕制图展开详细的内容展开更多相关内容,需要的小伙伴可以参考一下
    2022-06-06

最新评论