发送邮件使用smtp协议,pop3接收邮件
smtp有身份验证,登录邮件服务器时使用
1.建立java工程Jmail,建包com.sk.mail,建邮件发送类MailOper ,代码如下:
package com.sk.tools;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class MailOper {
private Auth auth;/*1授权*/
private Session session;/*2Session*/
private Transport transport;/*3Transport*/
private MimeMessage message;/*4MimeMessage*/
private MimeMultipart multipart;/*5MimeMultipart*/
private Properties props; /*属性*/
private String host="";
private String uid="";
private String pwd="";
public MailOper(){}
/**
*
* @param isAuth
* @param isDebug
* @param uid
* @param pwd
* @param host
*/
public MailOper(boolean isAuth,boolean isDebug,String uid,String pwd,String host){
props=System.getProperties();
if(isAuth){
auth=new MailOper.Auth(uid,pwd);
props.setProperty("mail.smtp.auth", "true");
}
props.setProperty("mail.smtp.host", host);
session=Session.getInstance(props,auth);
session.setDebug(isDebug);
message=new MimeMessage(session);
multipart=new MimeMultipart();
this.host=host;
this.uid=uid;
this.pwd=pwd;
}
/**
* 标题
* @param title
* @throws MessagingException
*/
public void setTitle(String title) throws MessagingException{
message.setSubject(title);
}
/**
* 正文
* @param content
* @throws MessagingException
*/
public void setContent(String content) throws MessagingException{
message.setText(content);
}
/**
* 发件人
* @param from
* @throws AddressException
* @throws MessagingException
*/
public void setFrom(String from) throws AddressException, MessagingException{
message.setFrom(new InternetAddress(from));
}
/**
* 收件人
* @param tos
* @throws MessagingException
*/
public void setTo(String[] tos) throws MessagingException{
if(tos!=null&& tos.length!=0){
InternetAddress[] addrs=new InternetAddress[tos.length];
for(int i=0;i<tos.length;i++){
addrs[i]=new InternetAddress(tos[i]);
}
message.setRecipients(RecipientType.TO, addrs);
}
}
/**
* 附件
* @param files
* @throws MessagingException
*/
public void setAttachments(File[] files) throws MessagingException{
if(files!=null){
for(int i=0;i<files.length;i++){
MimeBodyPart mbp=new MimeBodyPart();
mbp.setDataHandler(new DataHandler(new FileDataSource(files[i])));
multipart.addBodyPart(mbp);
}
}
}
/**
* 发送
* @throws MessagingException
*/
public void send() throws MessagingException{
transport=session.getTransport("smtp");
transport.connect(host, uid, pwd);
transport.send(message);
}
/**
* 发送邮件
* @param from
* @param to
* @param host
* @param isDebug
* @param msgText
* @param subject
* @param file
* @param uid
* @param pwd
* @throws AddressException
* @throws MessagingException
*/
public void sendMail(String from,String to,String host,boolean isDebug,String msgText,String subject,File file,
String uid,String pwd
) throws AddressException, MessagingException{
//授权
Auth auth=new MailOper.Auth(uid,pwd);
//属性
Properties prop=System.getProperties();
prop.setProperty("mail.smtp.host", host);
prop.setProperty("mail.smtp.auth", "true");
//Session
Session session=Session.getInstance(prop,auth);
session.setDebug(isDebug);
//MimeMessage
MimeMessage msg=new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
//InternetAddress
InternetAddress address[]={new InternetAddress(to)};
//receipient
msg.setRecipients(RecipientType.TO, address);
//subject
msg.setSubject(subject);
//1正文
MimeBodyPart bodyPart=new MimeBodyPart();
bodyPart.setText(msgText);
//2附件
MimeBodyPart mbp2=new MimeBodyPart();
mbp2.setDataHandler(new DataHandler(new FileDataSource(file)));
mbp2.setFileName(file.getName());
//MimeMultipart
MimeMultipart multipart=new MimeMultipart();
multipart.addBodyPart(bodyPart);
multipart.addBodyPart(mbp2);
msg.setContent(multipart);
msg.setSentDate(new Date());
//Transport
Transport transport=session.getTransport("smtp");
transport.connect(host, uid, pwd);
transport.send(msg);
System.out.println("Send ok");
}
/**
* 授权类
* @author LuckyStar
*/
class Auth extends javax.mail.Authenticator{
private String uid="";
private String pwd="";
public Auth(String uid,String pwd){
this.uid=uid;
this.pwd=pwd;
}
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(uid,pwd);
}
}
}
//___________________________________________
2.建类MailReceive,代码如下:
package com.sk.mail;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.Scanner;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
public class MailRevieve {
public void receive(String popserver,String username,String password){
//创建Store
Store store=null;
//创建Folder
Folder folder=null;
//创建Properties
Properties props=System.getProperties();
//创建Session
Session session=Session.getDefaultInstance(props);
session.setDebug(true);
try {
//获取 Store
store=session.getStore("pop3");
// 打开 通道
store.connect(popserver, username, password);
//获取INBOX
folder=store.getFolder("INBOX");
if(folder==null){
throw new Exception("no pop3 inbox");
}
//只读 打开INBOX
folder.open(Folder.READ_ONLY);
//获取内容
Message[] msgs= folder.getMessages();
// for(int i=0;i<msgs.length;i++){
// //读取内容
// this.readMessage(msgs[i]);
// }
this.readMessage(msgs[0]);
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try{
if (folder !=null)
folder.close(false);
if(store !=null)
store.close();
}catch(Exception e1){
}
}
}
//读取消息的方法
private void readMessage(Message msg){
PrintWriter out=null;
Scanner in=null;
try {
//获取发件人
String from=((InternetAddress)msg.getFrom()[0]).getPersonal();
if(from ==null){
((InternetAddress)msg.getFrom()[0]).getAddress();
}
System.out.println("发件人:"+from);
//主题
System.out.println("主题:"+msg.getSubject());
//主体
Part msgPart=msg; //Message 继承 Part
//获取 邮件主体
Object content= msgPart.getContent();
if(content instanceof Multipart){
msgPart=((Multipart)content).getBodyPart(0);
System.out.println("多部分multipart:");
//下载 邮件
out=new PrintWriter(new FileOutputStream("d:mail.txt",true),true);
in=new Scanner(msgPart.getInputStream());
while(in.hasNextLine()){
out.println(in.nextLine());
}
out.close();
in.close();
}
//contentType
String contentType=msgPart.getContentType();
System.out.println("内容类型:"+contentType);
//输出文本
if(contentType.startsWith("text/plain") || contentType.startsWith("text/html")){
in=new Scanner(msgPart.getInputStream());
System.out.println("正文内容:");
while(in.hasNextLine()){
System.out.println(in.nextLine());
}
System.out.println("结束");
}
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
new MailRevieve().receive("pop3.163.com", "username", "password");
}
}
//到此,可实现,附件带附件发送,接收带附件的邮件