1. 程式人生 > >java程式實現QQ郵件的傳送:

java程式實現QQ郵件的傳送:

1.要想遠端登入QQ必須做如下處理:參考如下:

通過以上文章可以實現用telnet工具命令列發qq郵件。

2.如果telnet命令不可識別:以下是win10安裝telnet方法參考如下:

3.java實現:

package com.cl.socket2_12;

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.net.Inet4Address;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.MessageFormat;

public class MailSender {
	private String smtpServer="smtp.qq.com";//SMTP郵件伺服器的主機名
	private int port=25;
	
	public static void main(String[] args) throws UnknownHostException, IOException {
		Message msg=new Message("
[email protected]
", //發件地址 "[email protected]", //收件方 "hello", //主題 "hi,I miss yuo very much."); //內容 new MailSender().sendMail(msg); } private void sendMail(Message msg) { Socket socket = null; try{ socket=new Socket(smtpServer,port); BufferedReader br=getReader(socket); //從伺服器讀 PrintWriter pw=getWriter(socket); //寫入aocket String localhost=Inet4Address.getLocalHost().getHostName(); //本地主機名 //郵箱登入賬號和密碼,編碼 String userID="
[email protected]
"; String pass="fbhcgilkeiapijge"; userID=new sun.misc.BASE64Encoder().encode(userID.getBytes()); pass=new sun.misc.BASE64Encoder().encode(pass.getBytes()); sendAndReceive(null,br,pw); //qq郵箱伺服器通訊過程:客戶端傳送的“”通過pw寫出 sendAndReceive("HELO "+localhost,br,pw); //qq郵箱伺服器特有的使用者驗證過程 sendAndReceive("STARTTLS auth login",br ,pw); sendAndReceive("auth login",br,pw); sendAndReceive(userID, br, pw); sendAndReceive(pass, br, pw); sendAndReceive("MAIL FROM:"+msg.from,br,pw); sendAndReceive("RCPT TO:"+msg.to,br,pw); sendAndReceive("DATA",br,pw); pw.println(msg.data); System.out.println("Cliet>"+msg.data); sendAndReceive(".",br,pw); sendAndReceive("QUIT",br,pw); }catch (Exception e) { e.printStackTrace(); }finally{ if(socket!=null){ try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * * @param str:客戶端傳送資訊 * @param br:讀取伺服器的響應訊息流 * @param pw:傳送到伺服器的流 * @throws IOException */ private void sendAndReceive(String str, BufferedReader br, PrintWriter pw) throws IOException { if(str!=null){ System.out.println("Client>"+str); pw.println(str); } String response; if((response=br.readLine())!=null){ System.out.println("Server>"+response); } } private BufferedReader getReader(Socket scoket) throws IOException{ InputStream in=scoket.getInputStream(); return new BufferedReader(new InputStreamReader(in)); } private PrintWriter getWriter(Socket socket) throws IOException{ OutputStream out=socket.getOutputStream(); return new PrintWriter(out,true); } } class Message{ String from; String to; String subject; String content; String data; public Message(String from, String to, String subject, String content) { super(); this.from = from; this.to = to; this.subject = subject; this.content = content; this.data="Subject:"+subject+"\r\n"+content; } }

4.以下是結果: 

結果