使用java發送QQ郵件的總結


       最近幫朋友做個網站,實現用郵箱訂閱功能,所以現在把這個發送郵件的功能放在這里,算是這兩天工作的總結吧!

首先,想要實現訂閱功能,要把郵箱保存,但是這個做的是個小網站,前后台交互的太少了,所以我就直接保存在了文件里面,用到的時候,直接讀取。

下面是保存郵箱號到本地文件的代碼。

 1 package ccom.llf.smfp;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.File;
 5 import java.io.FileNotFoundException;
 6 import java.io.FileReader;
 7 import java.io.FileWriter;
 8 import java.io.IOException;
 9 import java.io.PrintWriter;
10 
11 import javax.servlet.ServletException;
12 import javax.servlet.http.HttpServlet;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15 
16 public class SendEmail extends HttpServlet {
17      /**
18      * 如果是get請求就重寫doget方法,如果是其他的也是一樣對應的
19      */
20     @Override
21     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
22            String filename =this.getClass().getClassLoader().getResource("/").getPath()+"email.text";
23            String filename1 =this.getClass().getClassLoader().getResource("/").getPath()+"count.text";
24            /*filename = filename.substring(1, filename.length());
25           filename1 = filename1.substring(1, filename1.length());*/
26            response.setContentType("application/text; charset=utf-8");
27            PrintWriter out = response.getWriter();
28            
29            //判斷該郵箱時候已經訂閱過
30            FileReader fr=new FileReader(filename);
31            BufferedReader br=new BufferedReader(fr);
32            String line="";
33            String[] arrs=null;
34            while ((line=br.readLine())!=null) {
35               if(line.equals(request.getParameter("SendEmail").toString()+"\t")){
36                   out.write("1"); 
37                   return;
38               }
39            }
40            br.close();
41            fr.close();
42            
43            FileWriter writer = new FileWriter(filename, true);
44             //writer.write(request.getParameter("SendEmail").toString()+  ";"+"/r/n");
45             writer.write(request.getParameter("SendEmail").toString()+"\t\n");
46             writer.close();
47 
48              File f = new File(filename1);
49              int count = 0;
50              if (!f.exists()) {
51                  writeFile(filename1, 100);
52              }
53              try {
54                  BufferedReader in = new BufferedReader(new FileReader(f));
55                  try {
56                      count = Integer.parseInt(in.readLine())+1;
57                      writeFile(filename1, count);
58                      out.write(String.valueOf(count));
59                  } catch (NumberFormatException e) {
60                      e.printStackTrace();
61                  } catch (IOException e) {
62                      e.printStackTrace();
63                  }
64              } catch (FileNotFoundException e) {
65                  e.printStackTrace();
66              }
67              
68         
69     }
70 
71     public static void writeFile(String filename, int count) {
72 
73         try {
74             PrintWriter out = new PrintWriter(new FileWriter(filename));
75             out.println(count);
76             out.close();
77         } catch (IOException e) {
78             e.printStackTrace();
79         }
80     }
81 
82 }

這里用到的就是簡單的輸入輸出流 ,就不做過多的講解。

下面當腰發郵件的時候,需要開啟郵箱smtp服務,獲取授權碼。

我們的是qq郵箱,這里以qq郵箱為例,在QQ郵箱的設置——>賬號——>下拉有個pop3/smtp服務  開啟,獲取授權碼。。發郵件的時候,就用到授權碼,不直接用密碼,這樣防止賬戶安全吧。

package com.poi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail2 {

    private String host = "smtp.qq.com"; // smtp服務器
    private static String from = ""; // 發件人郵箱號
    private static String to = ""; // 收件人郵箱號
    private String affix = ""; // 附件地址
    private String affixName = ""; // 附件名稱
    private static String user = ""; // 用戶名
    private static String pwd = ""; // 授權碼
    private String subject = "hello"; // 郵件標題

    public void setAddress(String from, String to, String subject) {
        this.from = from;
        this.to = to;
        this.subject = subject;
    }

    public void setAffix(String affix, String affixName) {
        this.affix = affix;
        this.affixName = affixName;
    }

    public void send(String host, String user, String pwd) {
        this.host = host;
        this.user = user;
        this.pwd = pwd;

        Properties props = new Properties();

        // 設置發送郵件的郵件服務器的屬性(這里使用網易的smtp服務器)
        props.put("mail.smtp.host", host);
        // 需要經過授權,也就是有戶名和密碼的校驗,這樣才能通過驗證
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", 465);
        props.put("mail.smtp.ssl.enable", true);
        // 用剛剛設置好的props對象構建一個session
        Session session = Session.getDefaultInstance(props);

        // 有了這句便可以在發送郵件的過程中在console處顯示過程信息,供調試使
        // 用(你可以在控制台(console)上看到發送郵件的過程)
        session.setDebug(true);

        // 用session為參數定義消息對象
        MimeMessage message = new MimeMessage(session);
        try {
            // 加載發件人地址
            message.setFrom(new InternetAddress(from));
            // 加載收件人地址
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(
                    to));
            // 加載標題
            message.setSubject(subject);

            // 向multipart對象中添加郵件的各個部分內容,包括文本內容和附件
            Multipart multipart = new MimeMultipart();

            // 設置郵件的文本內容
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setText("第二種方法···");
            multipart.addBodyPart(contentPart);
            // 添加附件
            BodyPart messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(affix);
            // 添加附件的內容
            messageBodyPart.setDataHandler(new DataHandler(source));
            // 添加附件的標題
            // 這里很重要,通過下面的Base64編碼的轉換可以保證你的中文附件標題名在發送時不會變成亂碼
            sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
            messageBodyPart.setFileName("=?GBK?B?"
                    + enc.encode(affixName.getBytes()) + "?=");
            multipart.addBodyPart(messageBodyPart);

            // 將multipart對象放到message中
            message.setContent(multipart);
            // 保存郵件
            message.saveChanges();
            // 發送郵件
            Transport transport = session.getTransport("smtp");
            // 連接服務器的郵箱
            transport.connect(host, user, pwd);
            // 把郵件發送出去
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
     //先往你的本地寫一個文件,這樣附件就坑定存在了。
        File file = new File("D:\\22.cvg");
        try {
            OutputStream os = new FileOutputStream(file);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,
                    "utf-8"));
            bw.write("hello");
            bw.close();
            os.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            
        
        SendMail2 cn = new SendMail2();
        // 設置發件人地址、收件人地址和郵件標題
        cn.setAddress(from, to, user);
        // 設置要發送附件的位置和標題
        cn.setAffix("D:\\22.cvg", "22.cvg");
        // 設置smtp服務器以及郵箱的帳號和密碼
        cn.send("smtp.qq.com", from,pwd);
    }
}

這樣我們就可以發送郵件了。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM