关于javamail在android SDK中使用,网上已经有很多资料,这里不再赘述。
以下文章说下javamail在收发gmail邮箱进行收发邮件的一些设置
1.发送邮件
密码 验证
class PopupAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
String username = "zhouxufeng2012@gmail.com"; // 邮箱登录帐号
String pwd = "XXXXXX"; // 登录密码
return new PasswordAuthentication(username, pwd);
}
}
参数设置
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.ssl", "true");
props.setProperty("mail.smtp.starttls.enable","true");
PopupAuthenticator auth = new PopupAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage message = new MimeMessage(session);
Address addressFrom;
Address addressTo;
Address addressCopy;
addressFrom = new InternetAddress("zhouxufeng2012@gmail.com", "Johnson");
addressTo = new InternetAddress("zhouxufeng2012@gmail.com", "gZhou");
message.setText("中文测试");
message.setSubject("H--H");
message.setFrom(addressFrom);
message.addRecipient(Message.RecipientType.TO,addressTo);
message.addRecipient(Message.RecipientType.CC,addressCopy);
message.saveChanges();
Transport.send(message);
2.接收邮件
gmail接收邮件有两种方式,pop3方式和imap方式,pop3的我没有试过,贴下imap接收的代码
Properties props = new Properties();
props.setProperty("mail.imap.host", "imap.gmail.com");
props.put("mail.store.protocol", "imap");
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
//props.put("mail.imap.connectiontimeout", ConfigKeys.IMAP_CONNECTIONTIMEOUT);
props.setProperty("mail.imap.port", "993");
props.setProperty("mail.imap.socketFactory.port", "993");
PopupAuthenticator auth = new PopupAuthenticator();
Session session = Session.getInstance(props,auth);
session.setDebug(true);
Store store;
int count;
store = session.getStore();
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
Message msgs[] = folder.getMessages();
count = msgs.length;
System.out.println("Message Count:"+count);
ReciveMail rm = null;
for(int i=0;i<count;i++){
rm = new ReciveMail((MimeMessage) msgs[i]);
rm.recive(msgs[i],i);
System.out.println("Message:"+rm.getBodyText());
}
folder.close(true);
store.close();
3. 邮件删除
imap方式比pop3多的功能就是对邮箱的一些操作
在网上看到的一些大侠们说需要添加这么两句,就能实现接收后立即删除
msgs[i].setFlag(Flags.Flag.DELETED, true);
msgs[i].saveChanges();
但我试了下,仅上面一句就可以了,加上第二句反而会报错,如下
for(int i=0;i<count;i++){
rm = new ReciveMail((MimeMessage) msgs[i]);
rm.recive(msgs[i],i);
msgs[i].setFlag(Flags.Flag.DELETED, true);
//msgs[i].saveChanges();
}