基于Android的邮件收发

参考连接:http://blog.sina.com.cn/s/blog_56e5b1410101lael.html

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailSender {
private String host;
private String username;
private String password;


public MailSender(String host,String username,String password){
this.host = host;
this.username = username;
this.password = password;
}

public void send(String mailTo,String mailSubject,String mailBody) throws Exception{
this.send(mailTo, mailSubject, mailBody, null);
}

public void send(String mailTo,String mailSubject,String mailBody,String personalName) throws
Exception{
try{
Properties props=new Properties();
Authenticator auth = new Email_Autherticator();
//进行邮件服务器用户认证
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, auth);
// Session session = Session.getDefaultInstance(props, auth);
//设置session,和邮件服务器进行通讯。
MimeMessage message = new MimeMessage(session);
//message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
message.setSubject(mailSubject); // 设置邮件主题
message.setText(mailBody); // 设置邮件正文
message.setSentDate(new Date()); // 设置邮件发送日期
Address address = new InternetAddress(username, personalName);
message.setFrom(address); // 设置邮件发送者的地址
Address toAddress = new InternetAddress(mailTo); // 设置邮件接收方的地址
message.addRecipient(Message.RecipientType.TO, toAddress);
Transport.send(message); // 发送邮件
}catch (Exception ex){
ex.printStackTrace();
throw new Exception(ex.getMessage());
}
}

public class Email_Autherticator extends Authenticator{
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
}
}

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.mail.Flags;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class ReceiveMail {
private MimeMessage mimeMessage = null;
private StringBuffer mailContent = new StringBuffer();// 邮件内容
private String dataFormat = "yy-MM-dd HH:mm";

public ReceiveMail(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}

// MimeMessage设定
public void setMimeMessage(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}

public String getFrom() throws MessagingException {
InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
String addr = address[0].getAddress();
String name = address[0].getPersonal();
if (addr == null) {
addr = "";
}
if (name == null) {
name = "";
}
String nameAddr = name + "<" + addr + ">";
return nameAddr;
}

public String getMailAddress(String type) throws Exception {
String mailAddr = "";
String addType = type.toUpperCase(Locale.getDefault());
InternetAddress[] address = null;
if (addType.equals("TO")) {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
} else if (addType.equals("CC")) {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
} else if (addType.equals("BCC")) {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
} else {
System.out.println("error type!");
throw new Exception("Error emailaddr type!");
}
if (address != null) {
for (int i = 0; i < address.length; i++) {
String mailaddress = address[i].getAddress();
if (mailaddress != null) {
mailaddress = MimeUtility.decodeText(mailaddress);
} else {
mailaddress = "";
}
String name = address[i].getPersonal();
if (name != null) {
name = MimeUtility.decodeText(name);
} else {
name = "";
}
mailAddr = name + "<" + mailaddress + ">";
}
}
return mailAddr;
}

public String getSubject() {
String subject = "";
try {
subject = MimeUtility.decodeText(mimeMessage.getSubject());
if (subject == null) {
subject = "";
}
} catch (Exception e) {
}
return subject;
}

public String getSentData() throws MessagingException {
Date sentdata = mimeMessage.getSentDate();
if (sentdata != null) {
SimpleDateFormat format = new SimpleDateFormat(dataFormat,Locale.getDefault());
return format.format(sentdata);
} else {
return "不清楚";
}

}

public String getMailContent() throws Exception {
compileMailContent((Part) mimeMessage);
return mailContent.toString();
}

public void compileMailContent(Part part) throws Exception {
String contentType = part.getContentType();
int nameIndex = contentType.indexOf("name");
boolean connName = false;
if (nameIndex != -1) {
connName = true;
}
if (part.isMimeType("text/plain") && !connName) {
mailContent.append((String) part.getContent());
} else if (part.isMimeType("text/html") && !connName) {
mailContent.append((String) part.getContent());
} else if(part.isMimeType("multipart/*")){
Multipart multipart = (Multipart)part.getContent();
int counts = multipart.getCount();
for(int i=0;i compileMailContent(multipart.getBodyPart(i));
}
}else if(part.isMimeType("message/rfc822")){
compileMailContent((Part)part.getContent());
}else{}

}

public boolean getReplySign() throws MessagingException {
boolean replySign = false;
String needreply[] = mimeMessage.getHeader("Disposition-Notification-To");
if (needreply != null) {
replySign = true;
}
return replySign;
}

public String getMessageID() throws MessagingException {
return mimeMessage.getMessageID();
}

public boolean isNew() throws MessagingException {
boolean isnew = false;
Flags flags = ((Message) mimeMessage).getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
for (int i = 0; i < flag.length; i++) {
if (flag[i] == Flags.Flag.SEEN) {
isnew = true;
break;
}
}
return isnew;
}

public void setMailContent(StringBuffer mailContent) {
this.mailContent = mailContent;
}

public void setDataFormat(String dataFormat) {
this.dataFormat = dataFormat;
}

}

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.MimeMessage;

public class MailList {



private String host ; //pop3服务器
private String user ; //邮箱
private String password ; // 密码

private static MailList instance;
private List mailList;
private HashMap serviceHashMap;

public static MailList getInstance(){
if(instance==null){
instance=new MailList("pop.qq.com","[email protected]",密码);
}
return instance;
}

public String getUpdateUrlStr() throws Exception{
String urlStr=null;
if(serviceHashMap==null){
serviceHashMap=this.getServeHashMap();
}
if(serviceHashMap.get("update")==1){
urlStr=mailList.get(1).getSubject();
}
return urlStr;
}

public String getUserHelp() throws Exception{
String userandmoney=null;
if(serviceHashMap==null){
serviceHashMap=this.getServeHashMap();
}
if(serviceHashMap.get("userhelp")==1){
userandmoney=mailList.get(3).getSubject();
}
return userandmoney;
}

public int getAllUserHelp() throws Exception{
String userandmoney=null;
int money=0;
if(serviceHashMap==null){
serviceHashMap=this.getServeHashMap();
}
if(serviceHashMap.get("userhelp")==1){
userandmoney=mailList.get(3).getSubject();
}
if(userandmoney!=null && userandmoney.contains("all-user-100")){
money=Integer.parseInt(userandmoney.substring(userandmoney.lastIndexOf("-"+1),
userandmoney.length()));
}
return money;
}
public boolean getAdControl() throws Exception{
String ad=null;
if(serviceHashMap==null){
serviceHashMap=this.getServeHashMap();
}
if(serviceHashMap.get("adcontrol")==1){
ad=mailList.get(2).getSubject();
}
if(ad.equals("ad=close")){
return false;
}
return true;
}

public HashMap getServeHashMap() throws Exception{
serviceHashMap=new HashMap ();
if(mailList==null){
mailList=getAllMail("INBOX");
}
String serviceStr=mailList.get(0).getSubject();
if(serviceStr.contains("update 1.0=true")){
serviceHashMap.put("update", 1);
}else if(serviceStr.contains("update 1.0=false")){
serviceHashMap.put("update", 0);
}
if(serviceStr.contains("adcontrol 1.0=true")){
serviceHashMap.put("adcontrol", 1);
}else if(serviceStr.contains("adcontrol 1.0=false")){
serviceHashMap.put("adcontrol", 0);
}
if(serviceStr.contains("userhelp 1.0=true")){
serviceHashMap.put("userhelp", 1);
}else if(serviceStr.contains("userhelp 1.0=false")){
serviceHashMap.put("userhelp", 0);
}

return serviceHashMap;
}

public MailList(String popHost,String userAcount,String password){
this.host=popHost;
this.user=userAcount;
this.password=password;
}


public List getAllMail(String folderName) throws MessagingException{
List mailList=new ArrayList();

// 连接服务器
Session session = Session.getDefaultInstance(
System.getProperties(), null);
Store store = session.getStore("pop3");
store.connect(host,user, password);
// 打开文件夹
Folder folder = store.getFolder(folderName);
// folder = store.getFolder(folderName);
folder.open(Folder.READ_WRITE);
// 总的邮件数
int mailCount = folder.getMessageCount();
if (mailCount==0){
folder.close(true);
store.close();
return null;
}else{
// 取得所有的邮件
Message[] messages = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
// 自定义的邮件对象
ReceiveMail reciveMail=new ReceiveMail((MimeMessage)messages[i]);
reciveMail.setDataFormat("yy年MM月dd日 HH:mm");// 邮件收信时间格式设定
mailList.add(reciveMail);//添加到邮件列表中
}
// 关闭文件夹
// folder.close(true);
// store.close();
// 返回获取到的邮件
return mailList;
}
}

public void delete(int pos)throws MessagingException{

Properties props = new Properties();
// props.setProperty("mail.smtp.host", "smtp.sina.com");
props.setProperty("mail.smtp.auth", "true");
//props.setProperty("mail.transport.protocol", "smtp");
Session session = Session.getDefaultInstance(props,null);
URLName urlname = new URLName("pop3","pop.qq.com",110,null,"[email protected]",密码);
//URLName urlname = new URLName("pop3","pop.exmail.qq.com",110,null,"xxxxx","xxxxx");
Store store = session.getStore(urlname);
store.connect();
Folder folder = store.getFolder("INBOX");
// folder.open(Folder.READ_ONLY);
folder.open(Folder.READ_WRITE);
Message msgs[] = folder.getMessages();
// int count = msgs.length;
System.out.println("Message pos:"+pos);
msgs[pos].setFlag(Flags.Flag.DELETED, true);
//msgs[count-1].saveChanges();
//folder.expunge();
folder.close(true);
store.close();

}
}


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.MessagingException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {

// TextView tvInfo;
Button btnSend, btnReceive;
ListView lsMessage;

MailList mailList;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectDiskReads()
// .detectDiskWrites()
// .detectNetwork()
// .penaltyLog()
// .build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectLeakedSqlLiteObjects()
// .detectLeakedClosableObjects()
// .penaltyLog()
// .penaltyDeath()
// .build());



mailList = new MailList("pop.qq.com", "[email protected]", 密码);

btnSend = (Button) findViewById(R.id.btnSentMessage);
btnReceive = (Button) findViewById(R.id.btnReceiveMessage);
lsMessage = (ListView) findViewById(R.id.lsMessage);

btnSend.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
SendAsyTask task = new SendAsyTask(MainActivity.this);
task.execute();
}
});

btnReceive.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
ReceiveAsyTask task=new ReceiveAsyTask(MainActivity.this);
task.execute();
}
});

lsMessage.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

@Override
public boolean onItemLongClick(AdapterView arg0, View arg1, final int arg2, long arg3) {
AlertDialog.Builder alert=new AlertDialog.Builder(MainActivity.this);
alert.setTitle("确定要删除");
alert.setNeutralButton("取消", null);
alert.setPositiveButton("确定", new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DeleteAsyTask task=new DeleteAsyTask(MainActivity.this);
task.execute(arg2);
}
});
alert.show();

return false;
}
});;

}

private List> receiveMessage(){
List mails;
// MailList mailList = new MailList("pop.qq.com", "[email protected]", 密码);
List> listData = new ArrayList>();
try {
mails = mailList.getAllMail("INBOX");

if (mails != null) {
for (int i = 0; i < mails.size(); i++) {
Map map = new HashMap();
ReceiveMail reciveMail = mails.get(i);
String mail_date = reciveMail.getSentData();// 发件日期
String mail_subject = reciveMail.getSubject();// 标题

map.put("title", mail_date);
map.put("description", mail_subject);
listData.add(map);
}
}

} catch (MessagingException e) {
return null;
}


return listData;
}

class DeleteAsyTask extends AsyncTask {

Context mContext;
ProgressDialog mDialog = null;
SimpleAdapter listItemAdapter;

public DeleteAsyTask(Context context) {
mContext = context;
}

@Override
protected String doInBackground(Integer... arg0) {
try {
mailList.delete(arg0[0]);
List> datalist=receiveMessage();
if(datalist!=null){
listItemAdapter = new SimpleAdapter(MainActivity.this, datalist,
android.R.layout.simple_list_item_2, new String[] { "title",
"description" }, new int[] {
android.R.id.text1,
android.R.id.text2 });
return "1";
}else {
return null;
}
} catch (MessagingException e) {

return null;
}

}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mDialog.dismiss();

if (result != null && result.equals("1")) {
lsMessage.setAdapter(listItemAdapter);
Toast.makeText(mContext, "刪除成功!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "连接错误!", Toast.LENGTH_SHORT).show();
}

}

@Override
protected void onPreExecute() {
super.onPreExecute();

mDialog = new ProgressDialog(mContext);
mDialog.setMessage("请稍等……");
mDialog.setCancelable(false);
mDialog.show();

}

}

class ReceiveAsyTask extends AsyncTask {

Context mContext;
ProgressDialog mDialog = null;
SimpleAdapter listItemAdapter;

public ReceiveAsyTask(Context context) {
mContext = context;
}

@Override
protected String doInBackground(String... arg0) {
List> datalist=receiveMessage();
if(datalist!=null){
listItemAdapter = new SimpleAdapter(MainActivity.this, datalist,
android.R.layout.simple_list_item_2, new String[] { "title",
"description" }, new int[] {
android.R.id.text1,
android.R.id.text2 });
return "1";
}
else{
return null;
}

}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mDialog.dismiss();

if (result != null && result.equals("1")) {
lsMessage.setAdapter(listItemAdapter);
Toast.makeText(mContext, "接收成功!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "连接错误!", Toast.LENGTH_SHORT).show();
}

}

@Override
protected void onPreExecute() {
super.onPreExecute();

mDialog = new ProgressDialog(mContext);
mDialog.setMessage("请稍等……");
mDialog.setCancelable(false);
mDialog.show();

}

}

class SendAsyTask extends AsyncTask {

Context mContext;
ProgressDialog mDialog = null;

public SendAsyTask(Context context) {
mContext = context;
}

@Override
protected String doInBackground(String... arg0) {

MailSender mailSender = new MailSender("smtp.qq.com", "[email protected]", 密码);
// String mailTo = "[email protected]";
String mailTo = "[email protected]";
String mailSubject = "你好";
String mailBody = "你真好123456789111";
try {
mailSender.send(mailTo, mailSubject, mailBody);
} catch (Exception e) {
return null;
}
return "1";
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mDialog.dismiss();

if (result != null && result.equals("1")) {
Toast.makeText(mContext, "发送成功!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, "连接错误!", Toast.LENGTH_SHORT).show();
}

}

@Override
protected void onPreExecute() {
super.onPreExecute();

mDialog = new ProgressDialog(mContext);
mDialog.setMessage("请稍等……");
mDialog.setCancelable(false);
mDialog.show();

}

}

}

别忘了权限:

你可能感兴趣的:(android)