- 浏览: 185368 次
- 性别:
- 来自: 浙江
文章分类
最新评论
基于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<counts;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<ReceiveMail> mailList;
private HashMap<String,Integer> serviceHashMap;
public static MailList getInstance(){
if(instance==null){
instance=new MailList("pop.qq.com","XXXXXX@qq.com",密码);
}
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<String,Integer> getServeHashMap() throws Exception{
serviceHashMap=new HashMap<String,Integer> ();
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<ReceiveMail> getAllMail(String folderName) throws MessagingException{
List<ReceiveMail> mailList=new ArrayList<ReceiveMail>();
// 连接服务器
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,"XXXXXX@qq.com",密码);
//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", "XXXXXXX@qq.com", 密码);
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<Map<String, String>> receiveMessage(){
List<ReceiveMail> mails;
// MailList mailList = new MailList("pop.qq.com", "XXXXXX@qq.com", 密码);
List<Map<String, String>> listData = new ArrayList<Map<String, String>>();
try {
mails = mailList.getAllMail("INBOX");
if (mails != null) {
for (int i = 0; i < mails.size(); i++) {
Map<String, String> map = new HashMap<String, String>();
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<Integer, Integer, String> {
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<Map<String, String>> 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<String, Integer, String> {
Context mContext;
ProgressDialog mDialog = null;
SimpleAdapter listItemAdapter;
public ReceiveAsyTask(Context context) {
mContext = context;
}
@Override
protected String doInBackground(String... arg0) {
List<Map<String, String>> 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<String, Integer, String> {
Context mContext;
ProgressDialog mDialog = null;
public SendAsyTask(Context context) {
mContext = context;
}
@Override
protected String doInBackground(String... arg0) {
MailSender mailSender = new MailSender("smtp.qq.com", "XXXXXXX@qq.com", 密码);
// String mailTo = "XXXXXXX@163.com";
String mailTo = "XXXXXXX@qq.com";
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();
}
}
}
别忘了权限:<uses-permission android:name="android.permission.INTERNET" />
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<counts;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<ReceiveMail> mailList;
private HashMap<String,Integer> serviceHashMap;
public static MailList getInstance(){
if(instance==null){
instance=new MailList("pop.qq.com","XXXXXX@qq.com",密码);
}
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<String,Integer> getServeHashMap() throws Exception{
serviceHashMap=new HashMap<String,Integer> ();
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<ReceiveMail> getAllMail(String folderName) throws MessagingException{
List<ReceiveMail> mailList=new ArrayList<ReceiveMail>();
// 连接服务器
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,"XXXXXX@qq.com",密码);
//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", "XXXXXXX@qq.com", 密码);
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<Map<String, String>> receiveMessage(){
List<ReceiveMail> mails;
// MailList mailList = new MailList("pop.qq.com", "XXXXXX@qq.com", 密码);
List<Map<String, String>> listData = new ArrayList<Map<String, String>>();
try {
mails = mailList.getAllMail("INBOX");
if (mails != null) {
for (int i = 0; i < mails.size(); i++) {
Map<String, String> map = new HashMap<String, String>();
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<Integer, Integer, String> {
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<Map<String, String>> 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<String, Integer, String> {
Context mContext;
ProgressDialog mDialog = null;
SimpleAdapter listItemAdapter;
public ReceiveAsyTask(Context context) {
mContext = context;
}
@Override
protected String doInBackground(String... arg0) {
List<Map<String, String>> 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<String, Integer, String> {
Context mContext;
ProgressDialog mDialog = null;
public SendAsyTask(Context context) {
mContext = context;
}
@Override
protected String doInBackground(String... arg0) {
MailSender mailSender = new MailSender("smtp.qq.com", "XXXXXXX@qq.com", 密码);
// String mailTo = "XXXXXXX@163.com";
String mailTo = "XXXXXXX@qq.com";
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();
}
}
}
别忘了权限:<uses-permission android:name="android.permission.INTERNET" />
- mail_jar.rar (484.2 KB)
- 下载次数: 62
相关推荐
以下将详细阐述基于Android平台的邮件收发系统的关键知识点。 首先,**Android开发环境**是基础,开发者需要熟悉Android Studio,这是Google官方推荐的集成开发环境,用于编写、调试和测试Android应用程序。安装...
【邮件收发软件】是基于Android平台开发的一个实例应用,主要功能是实现电子邮件的发送和接收。这个项目,名为AndroidEmail,为开发者提供了一个基础的框架,以理解如何在Android设备上集成邮件通信功能。 首先,...
【Android邮件客户端系统详解】 在移动设备上,一个基于Android的邮件客户端系统是用户与电子邮件交互的重要工具。这种系统允许用户方便地收发邮件,管理邮箱,并与其他应用程序集成,提高工作效率。本文将深入探讨...
在提供的文件列表中,“安卓.rar”可能包含了一个Android平台下的邮件收发示例,因为Android系统也广泛支持邮件API进行邮件操作。Android使用Java编程,虽然不是MFC,但原理相似,通常会使用Android的JavaMail API...
在Android平台上,开发一款能实现邮件收发的应用是一项常见的任务。AndroidEmail项目是针对这一需求提供的一个源码示例,它允许用户发送和接收电子邮件。本文将深入解析这个项目的相关知识点,帮助开发者理解和掌握...
本项目是一个基于安卓的完整邮件客户端客户端项目源码,使用javamail框架,使用pop3和stmp协议收发邮件,支持多附件收发和可选自动登录, 邮件内容解析支持多种编码,html内容自动用webview显示。项目压缩包说明里面...
基于android平台的手机邮箱开发,本次的课程设计选题为电子邮箱,邮箱的意义很简单,传递信息。但这与传统的实体邮箱有着很大的不同,源码和文档都包含。
【基于Android的手机邮件系统】是一个专为移动设备设计的应用程序,主要功能是实现电子邮件的发送和接收。在Android平台上构建这样的系统,开发者通常会利用JavaMail API来处理邮件服务的相关操作,因为JavaMail是一...
【Android邮件客户端】是一款基于Android平台的个人毕业设计项目,主要功能是实现用户收发电子邮件。这个项目在2014年完成,虽然随着时间的推移,某些技术可能已过时,但作为学习资料,仍然对初学者具有一定的参考...
Android是一个基于Linux内核的开源操作系统,主要用于移动设备如智能手机和平板电脑。它提供了丰富的API,允许开发者使用Java或Kotlin等语言进行应用程序开发。在MailDemo项目中,开发者将运用Android的Activity、...
1. 邮件收发:系统需要支持SMTP(Simple Mail Transfer Protocol)协议来发送邮件,以及POP3(Post Office Protocol version 3)或IMAP(Internet Message Access Protocol)协议来接收邮件。SMTP用于从用户代理到...
3. 邮件收发:通过POP3和SMTP协议,实现邮件的接收和发送,支持附件、多媒体内容等。 4. 目录管理:提供收件箱、发件箱、草稿箱、垃圾邮件等分类,便于用户管理和查找邮件。 5. 搜索功能:内置强大的搜索引擎,用户...
摘要:随着移动通信技术和网络技术的迅速发展,手机系统发生了巨大的变化,从进行简单通话功能的非智能手机到现在集上网、聊天、收发邮件、视屏电话会议等各种服务于娱乐为一身的智能手机系统。本文基于 Android ...
### 基于Android手机短信管理系统设计 #### 一、课题背景与研究意义 随着智能手机在日常生活中的普及,其已成为获取信息的重要工具。本研究针对当前市场上流行的多种移动操作系统(如Symbian、Windows Mobile、Mac...
基于移动网络的推送邮件系统与邮件的收发方法在其中扮演了重要角色。这类系统允许玩家在任何时间、任何地点接收和发送游戏内的邮件,极大地增强了游戏体验和玩家间的交流效率。 推送邮件系统的核心在于实时性。传统...
【基于Java的电子邮件收发系统设计与实现】 Java语言凭借其跨平台的特性以及丰富的类库,成为开发电子邮件系统的一种理想选择。本文将探讨如何利用Java技术构建一个完整的电子邮件收发系统,涵盖系统设计的基本原则...
随着移动通信技术和网络技术的迅速发展,手机系统发生了巨大的变化,从进行简单通话功能的非智能手机到现在集上网、聊天、收发邮件、视屏电话会议等各种服务于娱乐为一身的智能手机系统。Google 公司牵头成立了 OMS ...
2. 移动通信技术和网络技术发展对手机系统的影响:随着移动通信技术和网络技术的迅速发展,手机系统发生了巨大的变化,从进行简单通话功能的非智能手机到现在集上网、聊天、收发邮件、视屏电话会议等各种服务于娱乐...