使用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);
}
}
这样我们就可以发送邮件了。。。
赞 (0)
