java收发邮件(转)
2014-06-09 14:01 夜半花开 阅读(532) 评论(0) 编辑 收藏 举报转自:http://www.myexception.cn/program/838286.html
JAVA使用IMAP、POP3、SMTP协议收发邮件
1 package com.gatgets.mail; 2 3 import java.io.UnsupportedEncodingException; 4 5 import java.util.Date; 6 7 import java.util.Properties; 8 9 import javax.mail.Authenticator; 10 11 import javax.mail.FetchProfile; 12 13 import javax.mail.Folder; 14 15 import javax.mail.Message; 16 17 import javax.mail.Message.RecipientType; 18 19 import javax.mail.PasswordAuthentication; 20 21 import javax.mail.Session; 22 23 import javax.mail.Store; 24 25 import javax.mail.Transport; 26 27 import javax.mail.internet.InternetAddress; 28 29 import javax.mail.internet.MimeMessage; 30 31 import javax.mail.internet.MimeUtility; 32 33 34 35 36 /** 37 38 * 邮件工具类 39 40 * 需要导入mail.jar包(j2ee自带) 41 42 * @author 王正镇 43 44 * @date 2011-8-14 45 46 */ 47 48 public class EmailUtil { 49 50 51 52 53 private String username = null; // 邮箱用户名 54 55 private String password = null; // 邮箱密码 56 57 58 59 60 /** 61 62 * 传入自己的邮箱用户名和密码 63 64 * @param username 65 66 * @param password 67 68 */ 69 70 public EmailUtil(String username, String password) { 71 72 this.username = username; 73 74 this.password = password; 75 76 } 77 78 79 /** 80 81 * 创建连接会话 82 83 * @param props 84 85 * @return 86 87 */ 88 89 public Session createSession(Properties props) { 90 91 92 Session session = Session.getInstance(props, new Authenticator() { 93 94 // 返回用户名密码认证 95 96 @Override 97 98 public PasswordAuthentication getPasswordAuthentication() { 99 100 PasswordAuthentication pa = new PasswordAuthentication(username, password); 101 102 return pa; 103 104 } 105 106 }); 107 108 109 return session; 110 111 } 112 113 114 115 116 /** 117 118 * 发送邮件(需设置SMTP) 119 120 * @throws Exception 121 122 */ 123 124 public void sendMail(Properties props, SendEmailMessage sem) throws Exception { 125 126 127 Session session = createSession(props); 128 129 130 // 消息 131 132 Message msg = new MimeMessage(session); 133 134 msg.setFrom(InternetAddress.parse(MimeUtility.decodeText(sem.getFrom()))[0]); 135 136 // TO为初级收件人,CC为邮件副本抄送,BCC应该是密秘抄送吧 137 138 msg.setRecipients(RecipientType.TO, InternetAddress.parse(sem.getRecipient())); 139 140 msg.setSubject(sem.getSubject()); 141 142 msg.setText(sem.getText()); 143 144 msg.setSentDate(new Date()); 145 146 147 // 发送消息 148 149 Transport.send(msg); 150 151 } 152 153 154 /** 155 156 * 接收邮件(需设置POP3或SAMP) 157 158 * @throws Exception 159 160 */ 161 162 public void receiveMail(Properties props, String protocol) throws Exception { 163 164 165 Session session = createSession(props); 166 167 Store store = session.getStore(protocol); 168 169 store.connect(); // 连接 170 171 Folder inbox = store.getFolder("INBOX"); // 进入根目录 172 173 inbox.open(Folder.READ_WRITE); // 只读方式 174 175 FetchProfile profile = new FetchProfile(); 176 177 profile.add(FetchProfile.Item.ENVELOPE); // 获取信封 178 179 Message[] msgs = inbox.getMessages(); // 得到所有邮件 180 181 inbox.fetch(msgs, profile); // 预获取信息 182 183 // 打印 184 185 for (int i = 0; i < msgs.length; i++) { 186 187 System.out.println("发送时间:" + msgs[i].getSentDate()); 188 189 System.out.println("发送人:" + decodeText(msgs[i].getFrom()[0].toString())); 190 191 System.out.println("大小:" + msgs[i].getSize()); 192 193 System.out.println("标题:" + msgs[i].getSubject()); 194 195 System.out.println("内容" + msgs[i].getContent()); 196 197 System.out.println("-------------------"); 198 199 } 200 201 202 store.close(); 203 204 } 205 206 207 /** 208 209 * 处理中文编码问题 210 211 * @param text 212 213 * @return 214 215 * @throws UnsupportedEncodingException 216 217 */ 218 219 private String decodeText(String text) throws UnsupportedEncodingException { 220 221 222 if (text == null) { 223 224 return null; 225 226 } 227 228 229 if (text.startsWith("=?GB") || text.startsWith("=?gb")) 230 231 text = MimeUtility.decodeText(text); 232 233 else 234 235 text = new String(text.getBytes("ISO8859_1")); 236 237 return text; 238 239 } 240 241 242 243 }
1 package com.gatgets.mail; 2 3 import java.util.Properties; 4 /** 5 * 邮件默认配置类 6 * 方法中的必要参好,可根据实际情况修改 7 * @author 王正镇 8 * @date 2011-8-14 9 */ 10 public class DefaultConfigurer { 11 12 /** 13 * 获取SMTP默认配置 14 * @return 15 */ 16 public static Properties getSMTP() { 17 Properties p = new Properties(); 18 p.setProperty("mail.smtp.host", "smtp.qq.com"); // 按需要更改 19 p.setProperty("mail.smtp.protocol", "smtp"); 20 p.setProperty("mail.smtp.port", "465"); 21 p.setProperty("mail.smtp.auth", "true"); 22 // SSL安全连接参数 23 p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 24 p.setProperty("mail.smtp.socketFactory.fallback", "false"); 25 p.setProperty("mail.smtp.socketFactory.port", "465"); 26 return p; 27 } 28 /** 29 * 获取POP3收信配置 30 * @return 31 */ 32 public static Properties getPOP3() { 33 Properties p = new Properties(); 34 p.setProperty("mail.pop3.host", "pop.qq.com"); // 按需要更改 35 p.setProperty("mail.pop3.port", "995"); 36 // SSL安全连接参数 37 p.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 38 p.setProperty("mail.pop3.socketFactory.fallback", "false"); 39 p.setProperty("mail.pop3.socketFactory.port", "995"); 40 return p;} 41 /** 42 * 获取IMAP收信配置 43 * @return 44 */ 45 public static Properties getIMAP() { 46 Properties p = new Properties(); 47 p.setProperty("mail.imap.host", "imap.qq.com"); // 按需要更改 48 p.setProperty("mail.imap.port", "993"); 49 // SSL安全连接参数 50 p.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 51 p.setProperty("mail.imap.socketFactory.fallback", "false"); 52 p.setProperty("mail.imap.socketFactory.port", "993"); 53 return p;} 54 }
1 package com.gatgets.mail; 2 3 /** 4 * 发送邮件消息包装属性类 5 * 6 * @author 王正镇 7 * @date 2011-8-14 8 */ 9 public class SendEmailMessage { 10 11 12 private String type; // 格式类型,如 text/html;charset=gbk 13 private String from; // 发送人 14 private String subject; // 标题 15 private String text; // 内容 16 private String recipient; // 接收人,多个接收人用逗号分隔 17 private String datetime; // 发送时间 18 19 20 public String getFrom() { 21 return from; 22 } 23 24 25 public void setFrom(String from) { 26 this.from = from; 27 } 28 29 30 public String getSubject() { 31 return subject; 32 } 33 34 35 public void setSubject(String subject) { 36 this.subject = subject; 37 } 38 39 40 public String getText() { 41 return text; 42 } 43 44 45 public void setText(String text) { 46 this.text = text; 47 } 48 49 50 public String getRecipient() { 51 return recipient; 52 } 53 54 55 public void setRecipient(String recipient) { 56 this.recipient = recipient; 57 } 58 59 60 public String getDatetime() { 61 return datetime; 62 } 63 64 65 public void setDatetime(String datetime) { 66 this.datetime = datetime; 67 } 68 69 70 public String getType() { 71 return type; 72 } 73 74 75 public void setType(String type) { 76 this.type = type; 77 } 78 79 80 }
测试类
package com.gatgets.mail; /** * 测试类 * @author 王正镇 * @date 2011-8-14 */ public class TestEmail { /** * 程序入口点 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // 默认情况下,在这里输入QQ号和密码,便可收信与发信 EmailUtil eu = new EmailUtil("xxx", "xxx"); SendEmailMessage sem = new SendEmailMessage(); sem.setFrom("wzz<xxx@gmail.com>"); sem.setRecipient("xxx@qq.com,zzz@163.com"); sem.setSubject("镇长"); sem.setText("hello world"); eu.sendMail(DefaultConfigurer.getSMTP(), sem); System.out.println("发送成功"); // 收邮件 eu.receiveMail(DefaultConfigurer.getPOP3(), "pop3"); // pop3收信 System.out.println("收取完毕"); // 使用IMAP收信会抛出 Failed to load IMAP envelope 异常 //eu.receiveMail(DefaultConfigurer.getIMAP(), "imap"); // imap收信 } }