Java Mail

本文介绍了一个使用 Java 编写的简单 SMTP 客户端程序,该程序能够通过指定的邮件服务器发送邮件。文章详细展示了如何进行邮件服务器认证、设置邮件内容及收发方等关键步骤。

 import java.io.BufferedReader; 
 import java.io.BufferedWriter; 
 import java.io.IOException; 
 import java.io.InputStreamReader; 
 import java.io.OutputStreamWriter; 
 import java.net.Socket; 
 import java.net.SocketException; 
 import java.net.UnknownHostException; 
 import java.util.StringTokenizer; 
  
 import sun.misc.BASE64Encoder; 
  
 public class SMTPClient { 
  
  private boolean debug=true; 
  BASE64Encoder encode=new BASE64Encoder();//用于加密后发送用户名和密码 
  public static void main(String[] args) throws UnknownHostException, IOException { 
   // TODO Auto-generated method stub 
   MailMessage message=new MailMessage(); 
   message.setFrom("zhenwen_xue@163.com");//发件人 
   message.setTo("zhenwen_xue@163.com");//收件人 
   String server="smtp.163.com";//邮件服务器 
   //String server="smtpcom.263xmail.com";//邮件服务器 
   message.setSubject("test");//邮件主题 
   message.setContent("test");//邮件内容 
   message.setDatafrom("zhenwen_xue@163.com");//发件人,在邮件的发件人栏目中显示 
   message.setDatato("zhenwen_xue@163.com");//收件人,在邮件的收件人栏目中显示 
   message.setUser("zhenwen_xue@163.com");//登陆邮箱的用户名 
   message.setPassword("555555");//登陆邮箱的密码 
    
   SMTPClient smtp=new SMTPClient(server,25); 
   boolean flag; 
   flag=smtp.sendMail(message,server); 
   if(flag){ 
    System.out.println("邮件发送成功!"); 
   } 
   else{ 
    System.out.println("邮件发送失败!"); 
   } 
  
  } 
  private Socket socket; 
  public SMTPClient(String server,int port) throws UnknownHostException, IOException{ 
   try{ 
    socket=new Socket(server,port); 
   }catch(SocketException e){ 
    System.out.println(e.getMessage()); 
   }catch(Exception e){ 
    e.printStackTrace(); 
   }finally{ 
    System.out.println("已经建立连接!"); 
   } 
  
  } 
  //注册到邮件服务器 
  public void helo(String server,BufferedReader in,BufferedWriter out) throws IOException{ 
   int result; 
   result=getResult(in); 
   //连接上邮件服务后,服务器给出220应答 
   if(result!=220){ 
    throw new IOException("连接服务器失败"); 
   } 
   result=sendServer("HELO "+server,in,out); 
   //HELO命令成功后返回250 
   if(result!=250) 
   { 
    throw new IOException("注册邮件服务器失败!"); 
   } 
  } 
   
  private int sendServer(String str,BufferedReader in,BufferedWriter out) throws IOException{ 
   out.write(str); 
   out.newLine(); 
   out.flush(); 
   if(debug) 
   { 
    System.out.println("已发送命令:"+str); 
   } 
   return getResult(in); 
  } 
  public int getResult(BufferedReader in){ 
   String line=""; 
   try{ 
    line=in.readLine(); 
    if(debug){ 
     System.out.println("服务器返回状态:"+line); 
    } 
   }catch(Exception e){ 
    e.printStackTrace(); 
   } 
   //从服务器返回消息中读出状态码,将其转换成整数返回 
   StringTokenizer st=new StringTokenizer(line," "); 
   return Integer.parseInt(st.nextToken()); 
  } 
   
  public void authLogin(MailMessage message,BufferedReader in,BufferedWriter out) throws IOException{ 
   int result; 
   result=sendServer("AUTH LOGIN",in,out); 
   if(result!=334){ 
    throw new IOException("用户验证失败!"); 
   } 
    
    result=sendServer(encode.encode(message.getUser().getBytes()),in,out); 
    if(result!=334){ 
    throw new IOException("用户名错误!");  
    } 
    result=sendServer(encode.encode(message.getPassword().getBytes()),in,out); 
    
    if(result!=235){ 
     throw new IOException("验证失败!");  
   } 
  } 
  //开始发送消息,邮件源地址 
  public void mailfrom(String source,BufferedReader in,BufferedWriter out) throws IOException{ 
   int result; 
   result=sendServer("MAIL FROM:<"+source+">",in,out); 
   if(result!=250){ 
    throw new IOException("指定源地址错误"); 
   } 
  } 
  // 设置邮件收件人 
  public void rcpt(String touchman,BufferedReader in,BufferedWriter out) throws IOException{ 
   int result; 
   result=sendServer("RCPT TO:<"+touchman+">",in,out); 
   if(result!=250){ 
    throw new IOException("指定目的地址错误!"); 
   } 
  } 
   
  //邮件体 
  public void data(String from,String to,String subject,String content,BufferedReader in,BufferedWriter out) throws IOException{ 
   int result; 
   result=sendServer("DATA",in,out); 
   //输入DATA回车后,若收到354应答后,继续输入邮件内容 
   if(result!=354){ 
    throw new IOException("不能发送数据"); 
   } 
   out.write("From: "+from); 
   out.newLine(); 
   out.write("To: "+to); 
   out.newLine(); 
   out.write("Subject: "+subject); 
   out.newLine(); 
   out.newLine(); 
   out.write(content); 
   out.newLine(); 
   //句号加回车结束邮件内容输入 
   result=sendServer(".",in,out); 
   System.out.println(result); 
   if(result!=250) 
   { 
    throw new IOException("发送数据错误"); 
   } 
  } 
   
  //退出 
  public void quit(BufferedReader in,BufferedWriter out) throws IOException{ 
   int result; 
   result=sendServer("QUIT",in,out); 
   if(result!=221){ 
    throw new IOException("未能正确退出"); 
   } 
  } 
   
  //发送邮件主程序 
  public boolean sendMail(MailMessage message,String server){ 
   try{ 
    BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream())); 
    BufferedWriter out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); 
    helo(server,in,out);//HELO命令 
    authLogin(message,in,out);//AUTH LOGIN命令 
    mailfrom(message.getFrom(),in,out);//MAIL FROM 
    rcpt(message.getTo(),in,out);//RCPT 
    data(message.getDatafrom(),message.getDatato(),message.getSubject(),message.getContent(),in,out);//DATA 
    quit(in,out);//QUIT 
   }catch(Exception e){ 
    e.printStackTrace(); 
    return false; 
     
   } 
   return true; 
  } 
  
 } 

 public class MailMessage { 
   
  private String from; 
  private String to; 
  private String datafrom; 
  private String datato; 
  private String subject; 
  private String content; 
  private String date; 
  private String user; 
  private String password; 
  
  public String getPassword() { 
   return password; 
  } 
  
  public void setPassword(String password) { 
   this.password = password; 
  } 
  
  public String getUser() { 
   return user; 
  } 
  
  public void setUser(String user) { 
   this.user = user; 
  } 
  
  public String getContent() { 
   return content; 
  } 
  
  public void setContent(String content) { 
   this.content = content; 
  } 
  
  public String getDatafrom() { 
   return datafrom; 
  } 
  
  public void setDatafrom(String datafrom) { 
   this.datafrom = datafrom; 
  } 
  
  public String getDatato() { 
   return datato; 
  } 
  
  public void setDatato(String datato) { 
   this.datato = datato; 
  } 
  
  public String getDate() { 
   return date; 
  } 
  
  public void setDate(String date) { 
   this.date = date; 
  } 
  
  public String getFrom() { 
   return from; 
  } 
  
  public void setFrom(String from) { 
   this.from = from; 
  } 
  
  public String getSubject() { 
   return subject; 
  } 
  
  public void setSubject(String subject) { 
   this.subject = subject; 
  } 
  
  public String getTo() { 
   return to; 
  } 
  
  public void setTo(String to) { 
   this.to = to; 
  } 
  
 }

Java Mail 是一组用于发送和接收电子邮件的 API。它是 Java 标准版(Java SE)的一部分,因此不需要外部库或包。使用 Java Mail API,您可以从 Java 应用程序中发送电子邮件,也可以接收来自邮件服务器的电子邮件。Java Mail API 支持多种邮件传输协议,例如 SMTP、IMAP 和 POP3。 要使用 Java Mail API,您需要导入以下两个包: - javax.mail:这是 Java Mail API 的主要包,包含各种类和接口,用于发送和接收电子邮件。 - javax.mail.internet:这个包包含各种类和接口,用于处理邮件消息中的各种 MIME 类型,例如文本、HTML、图像等。 以下是一个简单的 Java Mail 示例,用于从 Gmail 发送电子邮件: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class SendEmail { public static void main(String[] args) { // 收件人电子邮件地址 String to = "recipient@example.com"; // 发件人电子邮件地址 String from = "sender@example.com"; // Gmail SMTP 服务器地址 String host = "smtp.gmail.com"; // Gmail SMTP 服务器端口 int port = 587; // 收件人邮箱密码(如果需要的话) String password = "recipient_password"; // 配置 Java Mail 属性 Properties properties = System.getProperties(); properties.put("mail.smtp.host", host); properties.put("mail.smtp.port", port); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.starttls.enable", "true"); // 创建一个新的 Session 对象 Session session = Session.getInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { // 创建一个新的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // 设置发件人和收件人 message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置电子邮件主题和正文 message.setSubject("Java Mail Example"); message.setText("This is a Java Mail example message."); // 发送消息 Transport.send(message); System.out.println("Message sent successfully!"); } catch (MessagingException mex) { mex.printStackTrace(); } } } ``` 在上面的示例中,我们使用 Gmail SMTP 服务器发送电子邮件。要使用其他邮件服务器,您需要更改 host 和 port 属性以及身份验证信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值