㈠ javamail開發郵件系統問題,能成功發送,怎麼樣接收呢
String username="[email protected]";
String password="xxxxxx";
Properties props = new Properties();
Session s = Session.getInstance(props);
Store store = s.getStore("pop3");
store.connect("pop.qq.com", username, password);
Folder folder = store.getFolder("Inbox");
folder.open(Folder.READ_WRITE);
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
Message arraymessage[] = folder.getMessages();
System.out.println("收件箱的郵件數:" + arraymessage.length);
for (int i = 0; i < arraymessage.length; i++) {
// 郵件發送者
String from = arraymessage[i].getFrom()[0].toString();
InternetAddress ia = new InternetAddress(from);
System.out.println("FROM:" + ia.getPersonal() + '('+ ia.getAddress() + ')');
// 郵件標題
System.out.println("TITLE:" + arraymessage[i].getSubject());
// 郵件大小
System.out.println("SIZE:" + arraymessage[i].getSize());
// 郵件發送時間
Date sentdate = (Date) arraymessage[i].getSentDate();
SimpleDateFormat format = new SimpleDateFormat("yy-MM-ddHH:mm");
//System.out.println(format.format(sentdate));
if(format.format(sentdate)==null){
System.out.println("DATE:無");
}else{
System.out.println("DATE:" + format.format(sentdate));}
System.out.println("type:"+arraymessage[i].getContentType());
System.out.println("content:"+arraymessage[i].getContent());
}
folder.close(false);
store.close();
} catch (Exception ee) {
ee.printStackTrace();
}
Message arraymessage[] = folder.getMessages();
folder.fetch(arraymessage, profile);
㈡ 用javamail接收企業郵箱里的郵件信息的問題
這是一封網易企業郵箱正常發件郵件的顯示格式可以對比下
發件人:"雲計算" <w****@***.com>
收件人:"****@***.com" <*****@***.com>
對比發件人:abc: def <[email protected]> def是屬於發件人的,abc:def應該都是發件人自定義昵稱,可以任意修改。
imap協議我們通常叫著郵件同步協議,你所用的郵件系統要確定是否支持該一協議。 覺得可以,請給分,謝謝了。
㈢ 運用JavaMail收郵件怎麼解決
javax.mail.Store:該類實現特定郵件協議(如POP3)上的讀、寫、監視、查找等操作。通過它的getFolder方法打開一個javax.mail.Folder。
javax.mail.Folder:該類用於描述郵件的分級組織,如收件箱、草稿箱。它的open方法打開分級組織,close方法關閉分級組織,getMessages方法獲得分級組織中的郵件,getNewMessageCount方法獲得分級組織中新郵件的數量,getUnreadMessageCount方法獲得分級組織中未讀郵件的數量
根據MimeMessage的getFrom和getRecipients方法獲得郵件的發件人和收件人地址列表,得到的是InternetAddress數組,根據InternetAddress的getAddress方法獲得郵件地址,根據InternetAddress的getPersonal方法獲得郵件地址的個人信息。
MimeMessage的getSubject、getSentDate、getMessageID方法獲得郵件的主題、發送日期和郵件的ID(表示郵件)。
通過MimeMessage的getContent方法獲得郵件的內容,如果郵件是MIME郵件,那麼得到的是一個Multipart的對象,如果是一共普通的文本郵件,那麼得到的是BodyPart對象。Multipart可以包含多個BodyPart,而BodyPart本身又可以是Multipart。BodyPart的MimeType類型為「multipart/*」時,表示它是一個Mutipart。
㈣ javamail接收郵件時主題的亂碼問題
這個過程比較復雜,首先,你要使用msg.getContentType()來獲取contenttype,找出裡面的charset=來獲取編碼,如果這裡面沒有編碼,則使用getHeader方法來獲取"From","To","Subject"中的編碼(至少會有一個有),這裡面的編碼以"=?"開頭(形式一般為=?GBK?B?之類,其中的GBK就是編碼),獲取編碼後,對應使用
String subject = msg.getHeader("Subject", ",", false);//優先使用getHeader來獲取內容,不要使用getSubject,那個經過一次編碼處理,你以後會很麻煩
if (!StringUtil.isNull(你獲取的編碼)
&& StringUtil.isNull(ParseCode.getCharSet(subject))) {//郵件主題中不含編碼,則使用從From或To中獲取的編碼
subject = new String(subject.getBytes("ISO8859_1"),
你獲取的編碼);//這里轉碼
}
這樣你就能獲取所有中文主題了
㈤ 如何使用javamail 接收含有圖片和附件的唷考
參考代碼如下:
import javax.mail.*;
import java.util.*;
import java.io.*;
public class ReceiveMail {
//處理任何一種郵件都需要的方法
private void handle(Message msg) throws Exception {
System.out.println("郵件主題:" + msg.getSubject());
System.out.println("郵件作者:" + msg.getFrom()[0].toString());
System.out.println("發送日期:" + msg.getSentDate());
}
//處理文本郵件
private void handleText(Message msg) throws Exception {
this.handle(msg);
System.out.println("郵件內容:"+msg.getContent());
}
//處理Multipart郵件,包括了保存附件的功能
private static void handleMultipart(Message msg) throws Exception {
String disposition;
BodyPart part;
Multipart mp = (Multipart) msg.getContent();
//Miltipart的數量,用於除了多個part,比如多個附件
int mpCount = mp.getCount();
for (int m = 0; m < mpCount; m++) {
this.handle(msg);
part = mp.getBodyPart(m);
disposition = part.getDisposition();
//判斷是否有附件
if (disposition != null && disposition.equals(Part.ATTACHMENT))
{
//這個方法負責保存附件
saveAttach(part);
} else {
//不是附件,就只顯示文本內容
System.out.println(part.getContent());
}
}
}
private static void saveAttach(BodyPart part) throws Exception {
//得到未經處理的附件名字
String temp = part.getFileName();
//除去發送郵件時,對中文附件名編碼的頭和尾,得到正確的附件名
//(請參考發送郵件程序SendMail的附件名編碼部分)
String s = temp.substring(8, temp.indexOf("?="));
//文件名經過了base64編碼,下面是解碼
String fileName = base64Decoder(s);
System.out.println("有附件:" + fileName);
InputStream in = part.getInputStream();
FileOutputStream writer = new FileOutputStream(new File(
"保存附件的本地路徑"+ "\\"+fileName));
byte[] content = new byte[255];
int read = 0;
while ((read = in.read(content)) != -1) {
writer.write(content);
}
writer.close();
in.close();
}
//base64解碼
private static String base64Decoder(String s) throws Exception {
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] b = decoder.decodeBuffer(s);
return (new String(b));
}
public static void receive(String receiverMailBoxAddress, String username,String password) {
//本人用的是yahoo郵箱,故接受郵件使用yahoo的pop3郵件伺服器
String host = "pop.mail.yahoo.com.cn";
try {
//連接到郵件伺服器並獲得郵件
Properties prop = new Properties();
prop.put("mail.pop3.host", host);
Session session = Session.getDefaultInstance(prop);
Store store = session.getStore("pop3");
store.connect(host, username, password);
Folder inbox = store.getDefaultFolder().getFolder("INBOX");
//設置inbox對象屬性為可讀寫,這樣可以控制在讀完郵件後直接刪除該附件
inbox.open(Folder.READ_WRITE);
Message[] msg = inbox.getMessages();
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
inbox.fetch(msg, profile);
for (int i = 0; i < msg.length; i++) {
//標記此郵件的flag標志對象的DELETED位為true,可以在讀完郵件後直接刪除該附件,具體執行時間是在調用
//inbox.close()方法的時候
msg[i].setFlag(Flags.Flag.DELETED, true);
handleMultipart(msg[i]);
System.out.println("****************************");
}
if (inbox != null) {
//參數為true表明閱讀完此郵件後將其刪除,更多的屬性請參考mail.jar的API
inbox.close(true);
}
if (store != null) {
store.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
㈥ javamail接收郵件報錯
使用pop3j協議嘗試以下,看可能好使不
這個報錯是認證失敗了,可能用戶名密碼出錯。
認證失敗,還可能是連續的訪問,被郵件伺服器拒絕了,過一會在嘗試。
QQ郵箱 POP3 和 SMTP 伺服器地址設置如下:
POP3伺服器(埠110)pop.qq.com
SMTP伺服器(埠25) smtp.qq.com
SMTP伺服器需要身份驗證。
如果是設置POP3和SMTP的SSL加密方式,則埠如下:
imap伺服器(埠993)
POP3伺服器(埠995)
SMTP伺服器(埠465或587)。
㈦ 怎麼樣使用JavaMail發送和接收郵件
public class MailTest {
//發送的郵箱 內部代碼只適用qq郵箱
private static final String USER = "[email protected]";
//授權密碼 通過QQ郵箱設置->賬戶->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務->開啟POP3/SMTP服務獲取
private static final String PWD = "xxxxx";
private String[] to;
private String[] cc;//抄送
private String[] bcc;//密送
private String[] fileList;//附件
private String subject;//主題
private String content;//內容,可以用html語言寫
public void sendMessage() throws Exception {
// 配置發送郵件的環境屬性
final Properties props = new Properties();
//下面兩段代碼是設置ssl和埠,不設置發送不出去。
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
// 表示SMTP發送郵件,需要進行身份驗證
props.setProperty("mail.transport.protocol", "smtp");// 設置傳輸協議
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");//QQ郵箱的伺服器 如果是企業郵箱或者其他郵箱得更換該伺服器地址
// 發件人的賬號
props.put("mail.user", USER);
// 訪問SMTP服務時需要提供的密碼
props.put("mail.password", PWD);
// 構建授權信息,用於進行SMTP進行身份驗證
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用戶名、密碼
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用環境屬性和授權信息,創建郵件會話
Session mailSession = Session.getInstance(props, authenticator);
// 創建郵件消息
MimeMessage message = new MimeMessage(mailSession);
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
// 設置發件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
message.setFrom(form);
//發送
if (to != null) {
String toList = getMailList(to);
InternetAddress[] iaToList = new InternetAddress().parse(toList);
message.setRecipients(RecipientType.TO, iaToList); // 收件人
}
//抄送
if (cc != null) {
String toListcc = getMailList(cc);
InternetAddress[] iaToListcc = new InternetAddress().parse(toListcc);
message.setRecipients(RecipientType.CC, iaToListcc); // 抄送人
}
//密送
if (bcc != null) {
String toListbcc = getMailList(bcc);
InternetAddress[] iaToListbcc = new InternetAddress().parse(toListbcc);
message.setRecipients(RecipientType.BCC, iaToListbcc); // 密送人
}
message.setSentDate(new Date()); // 發送日期 該日期可以隨意寫,你可以寫上昨天的日期(效果很特別,親測,有興趣可以試試),或者抽象出來形成一個參數。
message.setSubject(subject); // 主題
message.setText(content); // 內容
//顯示以html格式的文本內容
messageBodyPart.setContent(content,"text/html;charset=utf-8");
multipart.addBodyPart(messageBodyPart);
//保存多個附件
if(fileList!=null){
addTach(fileList, multipart);
}
message.setContent(multipart);
// 發送郵件
Transport.send(message);
}
public void setTo(String[] to) {
this.to = to;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public void setBcc(String[] bcc) {
this.bcc = bcc;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setContent(String content) {
this.content = content;
}
public void setFileList(String[] fileList) {
this.fileList = fileList;
}
private String getMailList(String[] mailArray) {
StringBuffer toList = new StringBuffer();
int length = mailArray.length;
if (mailArray != null && length < 2) {
toList.append(mailArray[0]);
} else {
for (int i = 0; i < length; i++) {
toList.append(mailArray[i]);
if (i != (length - 1)) {
toList.append(",");
}
}
}
return toList.toString();
}
//添加多個附件
public void addTach(String fileList[], Multipart multipart) throws Exception {
for (int index = 0; index < fileList.length; index++) {
MimeBodyPart mailArchieve = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fileList[index]);
mailArchieve.setDataHandler(new DataHandler(fds));
mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),"UTF-8","B"));
multipart.addBodyPart(mailArchieve);
}
}
//以下是演示demo
public static void main(String args[]) {
MailTest mail = new MailTest();
mail.setSubject("java郵件");
mail.setContent("你好 這是第一個java 程序發送郵件");
//收件人 可以發給其他郵箱(163等) 下同
mail.setTo(new String[] {"[email protected]"});
//抄送
// mail.setCc(new String[] {"[email protected]","[email protected]"});
//密送
//mail.setBcc(new String[] {"[email protected]","[email protected]"});
//發送附件列表 可以寫絕對路徑 也可以寫相對路徑(起點是項目根目錄)
// mail.setFileList(new String[] {"D:\\aa.txt"});
//發送郵件
try {
mail.sendMessage();
System.out.println("發送郵件成功!");
} catch (Exception e) {
System.out.println("發送郵件失敗!");
e.printStackTrace();
}
}
}
㈧ javamail接收郵件怎麼解析內容
package com.ghy.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
public class PraseMimeMessage{
private MimeMessage mimeMessage=null;
private String saveAttachPath="";//附件下載後的存放目錄
private StringBuffer bodytext=new StringBuffer();
//存放郵件內容的StringBuffer對象
private String dateformat="yy-MM-ddHH:mm";//默認的日前顯示格式
/**
*構造函數,初始化一個MimeMessage對象
*/
public PraseMimeMessage() {
}
public PraseMimeMessage(MimeMessage mimeMessage) {
this.mimeMessage=mimeMessage;
}
public void setMimeMessage(MimeMessage mimeMessage){
this.mimeMessage=mimeMessage;
}
/**
*獲得發件人的地址和姓名
*/
public String getFrom1()throws Exception{
InternetAddress address[]=(InternetAddress[])mimeMessage.getFrom();
String from=address[0].getAddress();
if(from==null){
from="";
}
String personal=address[0].getPersonal();
if(personal==null){
personal="";
}
String fromaddr=personal+"<"+from+">";
return fromaddr;
}
/**
*獲得郵件的收件人,抄送,和密送的地址和姓名,根據所傳遞的參數的不同
*"to"----收件人"cc"---抄送人地址"bcc"---密送人地址
* @throws Exception */
public String getMailAddress(String type){
String mailaddr="";
try {
String addtype=type.toUpperCase();
InternetAddress []address=null;
if(addtype.equals("TO")||addtype.equals("CC")||addtype.equals("BBC")){
if(addtype.equals("TO")){
address=(InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.TO);
}
else if(addtype.equals("CC")){
address=(InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.CC);
}
else{
address=(InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.BCC);
}
if(address!=null){
for (int i = 0; i < address.length; i++) {
String email=address[i].getAddress();
if(email==null)email="";
else{
email=MimeUtility.decodeText(email);
}
String personal=address[i].getPersonal();
if(personal==null)personal="";
else{
personal=MimeUtility.decodeText(personal);
}
String compositeto=personal+"<"+email+">";
mailaddr+=","+compositeto;
}
mailaddr=mailaddr.substring(1);
}
}
else{
}
} catch (Exception e) {
// TODO: handle exception
}
return mailaddr;
}
/**
*獲得郵件主題
*/
public String getSubject()
{
String subject="";
try {
subject=MimeUtility.decodeText(mimeMessage.getSubject());
if(subject==null)subject="";
} catch (Exception e) {
// TODO: handle exception
}
return subject;
}
/**
*獲得郵件發送日期
*/
public String getSendDate()throws Exception{
Date senddate=mimeMessage.getSentDate();
SimpleDateFormat format=new SimpleDateFormat(dateformat);
return format.format(senddate);
}
/**
*解析郵件,把得到的郵件內容保存到一個StringBuffer對象中,解析郵件
*主要是根據MimeType類型的不同執行不同的操作,一步一步的解析
*/
public void getMailContent(Part part)throws Exception{
String contenttype=part.getContentType();
int nameindex=contenttype.indexOf("name");
boolean conname=false;
if(nameindex!=-1)conname=true;
if(part.isMimeType("text/plain")&&!conname){
bodytext.append((String)part.getContent());
}else if(part.isMimeType("text/html")&&!conname){
bodytext.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++){
getMailContent(multipart.getBodyPart(i));
}
}else if(part.isMimeType("message/rfc822")){
getMailContent((Part)part.getContent());
}
else{}
}
/**
*獲得郵件正文內容
*/
public String getBodyText(){
return bodytext.toString();
}
/**
*判斷此郵件是否需要回執,如果需要回執返回"true",否則返回"false"
* @throws MessagingException */
public boolean getReplySign() throws MessagingException{
boolean replysign=false;
String needreply[]=mimeMessage.getHeader("Disposition-Notification-To");
if(needreply!=null){
replysign=true;
}
return replysign;
}
/**
*獲得此郵件的Message-ID
* @throws MessagingException */
public String getMessageId() throws MessagingException{
return mimeMessage.getMessageID();
}
/**
*【判斷此郵件是否已讀,如果未讀返回返回false,反之返回true】
* @throws MessagingException */
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;
}
/**
*判斷此郵件是否包含附件
* @throws MessagingException */
public boolean isContainAttach(Part part) throws Exception{
boolean attachflag=false;
String contentType=part.getContentType();
if(part.isMimeType("multipart/*")){
Multipart mp=(Multipart)part.getContent();
//獲取附件名稱可能包含多個附件
for(int j=0;j<mp.getCount();j++){
BodyPart mpart=mp.getBodyPart(j);
String disposition=mpart.getDescription();
if((disposition!=null)&&((disposition.equals(Part.ATTACHMENT))||(disposition.equals(Part.INLINE)))){
attachflag=true;
}else if(mpart.isMimeType("multipart/*")){
attachflag=isContainAttach((Part)mpart);
}else{
String contype=mpart.getContentType();
if(contype.toLowerCase().indexOf("application")!=-1) attachflag=true;
if(contype.toLowerCase().indexOf("name")!=-1) attachflag=true;
}
}
}else if(part.isMimeType("message/rfc822")){
attachflag=isContainAttach((Part)part.getContent());
}
return attachflag;
}
/**
*【保存附件】
* @throws Exception
* @throws IOException
* @throws MessagingException
* @throws Exception */
public void saveAttachMent(Part part) throws Exception {
String fileName="";
if(part.isMimeType("multipart/*")){
Multipart mp=(Multipart)part.getContent();
for(int j=0;j<mp.getCount();j++){
BodyPart mpart=mp.getBodyPart(j);
String disposition=mpart.getDescription();
if((disposition!=null)&&((disposition.equals(Part.ATTACHMENT))||(disposition.equals(Part.INLINE)))){
fileName=mpart.getFileName();
if(fileName.toLowerCase().indexOf("GBK")!=-1){
fileName=MimeUtility.decodeText(fileName);
}
saveFile(fileName,mpart.getInputStream());
}
else if(mpart.isMimeType("multipart/*")){
fileName=mpart.getFileName();
}
else{
fileName=mpart.getFileName();
if((fileName!=null)){
fileName=MimeUtility.decodeText(fileName);
saveFile(fileName,mpart.getInputStream());
}
}
}
}
else if(part.isMimeType("message/rfc822")){
saveAttachMent((Part)part.getContent());
}
}
/**
*【設置附件存放路徑】
*/
public void setAttachPath(String attachpath){
this.saveAttachPath=attachpath;
}
/**
*【設置日期顯示格式】
*/
public void setDateFormat(String format){
this.dateformat=format;
}
/**
*【獲得附件存放路徑】
*/
public String getAttachPath()
{
return saveAttachPath;
}
/**
*【真正的保存附件到指定目錄里】
*/
private void saveFile(String fileName,InputStream in)throws Exception{
String osName=System.getProperty("os.name");
String storedir=getAttachPath();
String separator="";
if(osName==null)osName="";
if(osName.toLowerCase().indexOf("win")!=-1){
//如果是window 操作系統
separator="/";
if(storedir==null||storedir.equals(""))storedir="c:\tmp";
}
else{
//如果是其他的系統
separator="/";
storedir="/tmp";
}
File strorefile=new File(storedir+separator+fileName);
BufferedOutputStream bos=null;
BufferedInputStream bis=null;
try {
bos=new BufferedOutputStream(new FileOutputStream(strorefile));
bis=new BufferedInputStream(in);
int c;
while((c=bis.read())!=-1){
bos.write(c);
bos.flush();
}
} catch (Exception e) {
// TODO: handle exception
}finally{
bos.close();
bis.close();
}
}
/**
*PraseMimeMessage類測試
* @throws Exception */
public static void main(String[] args) throws Exception {
String host="pop3.sina.com.cn";
String username="guohuaiyong70345";
String password="071120";
Properties props=new Properties();
Session session=Session.getDefaultInstance(props,null);
Store store=session.getStore("pop3");
store.connect(host,username,password);
Folder folder=store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message message[]=folder.getMessages();
PraseMimeMessage pmm=null;
for (int i = 0; i < message.length; i++) {
System.out.println("****************************************第"+(i+1)+"封郵件**********************************");
pmm=new PraseMimeMessage((MimeMessage)message[i]);
System.out.println("主題 :"+pmm.getSubject());
pmm.setDateFormat("yy年MM月dd日 HH:mm");
System.out.println("發送時間 :"+pmm.getSendDate());
System.out.println("是否回執 :"+pmm.getReplySign());
System.out.println("是否包含附件 :"+pmm.isContainAttach((Part)message[i]));
System.out.println("發件人 :"+pmm.getFrom1());
System.out.println("收件人 :"+pmm.getMailAddress("TO"));
System.out.println("抄送地址 :"+pmm.getMailAddress("CC"));
System.out.println("密送地址 :"+pmm.getMailAddress("BCC"));
System.out.println("郵件ID :"+i+":"+pmm.getMessageId());
pmm.getMailContent((Part)message[i]); //根據內容的不同解析郵件
pmm.setAttachPath("c:/tmp/mail"); //設置郵件附件的保存路徑
pmm.saveAttachMent((Part)message[i]); //保存附件
System.out.println("郵件正文 :"+pmm.getBodyText());
System.out.println("*********************************第"+(i+1)+"封郵件結束*************************************");
}
}
}