导航:首页 > 编程语言 > javamail设置pop3

javamail设置pop3

发布时间:2024-11-10 19:52:41

java收发邮件过程中具体的功能是怎么实现的

qq邮箱为例:


packagemain;

importjava.util.Properties;

importjavax.mail.Authenticator;
importjavax.mail.MessagingException;
importjavax.mail.PasswordAuthentication;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMessage.RecipientType;


publicclassSendMessageService{
;
privateMimeMessagemessage;
privatePropertiesprops=newProperties();
publicstaticStringuserName;
publicstaticStringpassword;
;
;

SendMessageService(){
{
props.put("mail.smtp.auth","true");
props.put("mail.smtp.host","smtp.qq.com");
props.put("mail.smtp.port","587");
props.put("mail.user","[email protected]");//发送出去邮箱,
props.put("mail.password","在腾讯邮箱申请的SMTP服务码");

//用户名、密码
userName=props.getProperty("mail.user");
password=props.getProperty("mail.password");

//构建授权信息,用于进行SMTP进行身份验证
Authenticatorauthenticator=newAuthenticator(){
(){
(userName,password);
}
};
mailSession=Session.getInstance(props,authenticator);
message=newMimeMessage(mailSession);
InternetAddressform=newInternetAddress(props.getProperty("mail.user"));
message.setFrom(form);
}catch(MessagingExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}

}

/**参数,发送的邮件的标题,邮件的内容,目标邮箱地址**/
publicvoidsendEm(Stringstr,Stringcont,Stringmailbox){
try{
//添加目标邮箱地址
to=newInternetAddress(mailbox);
message.setRecipient(RecipientType.TO,to);
//设置邮件标题
message.setSubject(str);
//设置邮件的内容体
message.setContent(cont,"text/html;charset=UTF-8");
Transport.send(message);
}catch(MessagingExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}

publicstaticvoidmain(String[]args){
newSendMessageService().sendEm("hahhahahhaha","哈哈哈哈哈哈","[email protected]");
}
}

申请/SMTP服务 ,先进入邮箱,点击设置,账户设置,翻到下面的开启第二个IMAP/SMTP服务 ,会得到一个SMTP码,记住它,

㈡ javamail收发信件时,服务器,收发方的名称应该怎样设置才有效呢

package com.gwxc.hz.mail.demo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
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.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

public class ReciveOneMail {

/**
* 有一封邮件就需要建立一个ReciveMail对象
*/
private MimeMessage mimeMessage = null;
private String saveAttachPath = ""; // 附件下载后的存放目录
private StringBuffer bodytext = new StringBuffer();// 存放邮件内容
private String dateformat = "yy-MM-dd HH:mm"; // 默认的日前显示格式

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

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

/**
* 获得发件人的地址和姓名
*/
public String getFrom() 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"---密送人地址
*/
public String getMailAddress(String type) throws Exception {
String mailaddr = "";
String addtype = type.toUpperCase();
InternetAddress[] address = null;
if (addtype.equals("TO") || addtype.equals("CC")
|| addtype.equals("BCC")) {
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 {
throw new Exception("Error emailaddr type!");
}
return mailaddr;
}

/**
* 获得邮件主题
*/
public String getSubject() throws MessagingException {
String subject = "";
try {
subject = MimeUtility.decodeText(mimeMessage.getSubject());
if (subject == null)
subject = "";
} catch (Exception exce) {
}
return subject;
}

/**
* 获得邮件发送日期
*/
public String getSentDate() throws Exception {
Date sentdate = mimeMessage.getSentDate();
SimpleDateFormat format = new SimpleDateFormat(dateformat);
return format.format(sentdate);
}

/**
* 获得邮件正文内容
*/
public String getBodyText() {
return bodytext.toString();
}

/**
* 解析邮件,把得到的邮件内容保存到一个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;
System.out.println("CONTENTTYPE: " + contenttype);
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 {
}
}

/**
* 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
*/
public boolean getReplySign() throws MessagingException {
boolean replysign = false;
String needreply[] = mimeMessage
.getHeader("Disposition-Notification-To");
if (needreply != null) {
replysign = true;
}
return replysign;
}

/**
* 获得此邮件的Message-ID
*/
public String getMessageId() throws MessagingException {
return mimeMessage.getMessageID();
}

/**
* 【判断此邮件是否已读,如果未读返回返回false,反之返回true】
*/
public boolean isNew() throws MessagingException {
boolean isnew = false;
Flags flags = ((Message) mimeMessage).getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
System.out.println("flags's length: " + flag.length);
for (int i = 0; i < flag.length; i++) {
if (flag[i] == Flags.Flag.SEEN) {
isnew = true;
System.out.println("seen Message.......");
break;
}
}
return isnew;
}

/**
* 判断此邮件是否包含附件
*/
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 i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
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;
}

/**
* 【保存附件】
*/
public void saveAttachMent(Part part) throws Exception {
String fileName = "";
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE)))) {
fileName = mpart.getFileName();
if (fileName.toLowerCase().indexOf("gb2312") != -1) {
fileName = MimeUtility.decodeText(fileName);
}
saveFile(fileName, mpart.getInputStream());
} else if (mpart.isMimeType("multipart/*")) {
saveAttachMent(mpart);
} else {
fileName = mpart.getFileName();
if ((fileName != null)
&& (fileName.toLowerCase().indexOf("GB2312") != -1)) {
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) throws Exception {
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) {
separator = "\\";
if (storedir == null || storedir.equals(""))
storedir = "c:\\tmp";
} else {
separator = "/";
storedir = "/tmp";
}
File storefile = new File(storedir + separator + fileName);
System.out.println("storefile's path: " + storefile.toString());
// for(int i=0;storefile.exists();i++){
// storefile = new File(storedir+separator+fileName+i);
// }
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(storefile));
bis = new BufferedInputStream(in);
int c;
while ((c = bis.read()) != -1) {
bos.write(c);
bos.flush();
}
} catch (Exception exception) {
exception.printStackTrace();
throw new Exception("文件保存失败!");
} finally {
bos.close();
bis.close();
}
}

public static void main(String[] args) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
URLName urln = new URLName("pop3", "pop3.163.com", 110, null,
"dt_cj2004", "abcdefghij");
Store store = session.getStore(urln);
store.connect();

Folder folder = store.getFolder("spool");
//Folder folder = store.getFullName();

folder.open(Folder.READ_ONLY);
//System.out.println(folder.getNewMessageCount());

Message message[] = folder.getMessages();
System.out.println("Messages's length: " + message.length);
ReciveOneMail pmm = null;
/*

for (int i = 0; i < message.length; i++) {
System.out.println("======================");
pmm = new ReciveOneMail((MimeMessage) message[i]);
System.out
.println("Message " + i + " subject: " + pmm.getSubject());
System.out.println("Message " + i + " sentdate: "
+ pmm.getSentDate());
System.out.println("Message " + i + " replysign: "
+ pmm.getReplySign());
System.out.println("Message " + i + " hasRead: " + pmm.isNew());
System.out.println("Message " + i + " containAttachment: "
+ pmm.isContainAttach((Part) message[i]));
System.out.println("Message " + i + " form: " + pmm.getFrom());
System.out.println("Message " + i + " to: "
+ pmm.getMailAddress("to"));
System.out.println("Message " + i + " cc: "
+ pmm.getMailAddress("cc"));
System.out.println("Message " + i + " bcc: "
+ pmm.getMailAddress("bcc"));
pmm.setDateFormat("yy年MM月dd日 HH:mm");
System.out.println("Message " + i + " sentdate: "
+ pmm.getSentDate());
System.out.println("Message " + i + " Message-ID: "
+ pmm.getMessageId());
// 获得邮件内容===============
pmm.getMailContent((Part) message[i]);
System.out.println("Message " + i + " bodycontent: \r\n"
+ pmm.getBodyText());
pmm.setAttachPath("c:\\");
pmm.saveAttachMent((Part) message[i]);
}
*/
}
}

package com.gwxc.hz.mail.demo;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class MyMailTest {

/**
* @param args
*/
public static void main(String[] args) throws Exception {

// 会话===========================
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.auth", "true");// 需要验证
Session session = Session.getDefaultInstance(props, null);

// msg 设置=======================
MimeMessage mimeMsg = new MimeMessage(session);

// 设置标题
mimeMsg.setSubject("标题test");

// 设置内容----begin
Multipart mp = new MimeMultipart();

// 添加文本
BodyPart bp1 = new MimeBodyPart();
bp1.setContent("文本内容", "text/html;charset=GB2312");
mp.addBodyPart(bp1);

// 添加附件
BodyPart bp2 = new MimeBodyPart();
FileDataSource fileds = new FileDataSource("c:\\boot.ini");
bp2.setDataHandler(new DataHandler(fileds));
bp2.setFileName(fileds.getName());
mp.addBodyPart(bp2);

mimeMsg.setContent(mp);
// 设置内容----end

mimeMsg.setFrom(new InternetAddress("[email protected]"));
mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
.parse("[email protected]"));
mimeMsg.saveChanges();

// 传输==================================
Transport transport = session.getTransport("smtp");
transport.connect((String) props.get("mail.smtp.host"),
"xiangzhengyan", "pass");
transport.sendMessage(mimeMsg, mimeMsg
.getRecipients(Message.RecipientType.TO));
transport.close();
}

}

㈢ javamail怎么设置代理发送邮件

public static void main(String[] args) throws Exception {
MailTest test = new MailTest();
//通过代理发送邮件
test.sendMailByProxy();
}
private void sendMailByProxy()throws Exception{
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//设置代理服务器
Properties props = System.getProperties();
props.setProperty("proxySet", "true");
props.setProperty("socksProxyHost", "192.168.1.1");
props.setProperty("socksProxyPort", "1080");
props.setProperty("mail.smtp.host", "smtp.163.com");

//props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "25");
props.setProperty("mail.smtp.socketFactory.port", "25");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
final String username = "用户名";
final String password = "密码";

//使用验证
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username,
password);
}
});
MimeMessage message = new MimeMessage(session);
Address address = new InternetAddress("[email protected]");
Address toAaddress = new InternetAddress("[email protected]");

message.setFrom(address);
message.setRecipient(MimeMessage.RecipientType.TO, toAaddress);
message.setSubject("测试");
message.setText("test");
message.setSentDate(new Date());
Transport.send(message);
System.out.println("邮件发送!");
}

㈣ 利用javamail和POP3、SMPT协议实现邮件的收发

一 简介 SMTP 的全称是 Simple Mail Transfer Protocol 即简单邮件传输协议 用于邮件发送 SMTP 认证 简单地说就是要求必须在提供了账户名和密码之后才可以登录 SMTP 服务器 POP (Post Office Protocol )协议允许电子邮件客户端下载服务器上的邮件 但是在客户端的操作(如移动邮件 标记已读等) 不会反馈到服务器上 比如通过客户端收取了邮箱中的 封邮件并移动到其他文件夹 邮箱服务器上的这些邮件是没有同时被移动的 而IMAP(Internet Mail Access Protocol)提供webmail 与电子邮件客户端之间的双向通信 客户端的操作都会反馈到服务器上 对邮件进行的操作 服务器上的邮件也会做相应的动作 同时 IMAP像POP 那样提供了方便的邮件下载服务 让用户能进行离线阅读 IMAP提供的摘要浏览功能可以让你在阅读完所有的邮件到达时间 主题 发件人 大小等信息后才作出是否下载的决定 此外 IMAP 更好地支持了从多个不同设备中随时访问新邮件 总之 IMAP 整体上为用户带来更为便捷和可靠的体验 POP 更易丢失邮件或多次下载相同的邮件 但 IMAP 通过邮件客户端与webmail 之间的双向同步功能很好地避免了这些问题 注 若在web邮箱中设置了 保存到已发送 使用客户端POP服务发信时 已发邮件也会自动同步到网页端 已发送 文件夹内 二 利用SMTP协议发送邮件 package like email;import java io File;import java io UnsupportedEncodingException;import java util ArrayList;import java util Properties;import javax activation DataHandler;import javax activation DataSource;import javax activation FileDataSource;import javax mail Authenticator;import javax mail BodyPart;import javax mail Message;import javax mail MessagingException;import javax mail Multipart;import javax mail Session;import javax mail Transport;import javax mail internet AddressException;import javax mail internet InternetAddress;import javax mail internet MimeBodyPart;import javax mail internet MimeMessage;import javax mail internet MimeMultipart;/*** @author like* @E mail k* @CreateTime 下午 : : */public class SMTPSendTest {private static final int RECEIPT = ;private static final String attachmentDir = ;public static void sendEmail(Email emailInfo) throws UnsupportedEncodingException MessagingException {Properties props = new Properties() props put( mail *** tp host emailInfo getSmtpServer()) props put( mail *** tp port emailInfo getSmtpPort()) props put( mail *** tp auth true ) Authenticator auth = new SMTPAuthenticator(emailInfo getUsername() emailInfo getPassword()) Session session = Session getInstance(props auth) session setDebug(false) Message msg = new MimeMessage(session) msg setFrom(new InternetAddress(emailInfo getFrom() emailInfo getFromName())) msg setRecipients(Message RecipientType TO getEmailRecipient(emailInfo getTO())) msg setRecipients(Message RecipientType CC getEmailRecipient(emailInfo getCC())) msg setRecipients(Message RecipientType BCC getEmailRecipient(emailInfo getBCC())) if (emailInfo getReceipt() == RECEIPT) {msg setHeader( Disposition Notification To emailInfo getFrom()) }msg setSubject(emailInfo getSubject()) // 设置邮件内容(包括附件的HTML格式内容)msg setContent(getMultipart(emailInfo getContent() attachmentDir emailInfo getAttachment())) msg saveChanges() Transport send(msg) }/*** 封装邮件地址** @param address* @return* @throws AddressException*/private static InternetAddress[] getEmailRecipient(ArrayList<String> address) throws AddressException {int toLen = ;if (address != null) {toLen = address size() }InternetAddress[] addressTo = new InternetAddress[toLen];if (toLen != ) {String m_st_email = ;for (int i = ; i < toLen; i++) {m_st_email = (String) address get(i) if (m_st_email != null)addressTo[i] = new InternetAddress(m_st_email trim()) }}return addressTo;}private static Multipart getMultipart(String text String attachParentDir ArrayList<String> attachment) throws MessagingException {

lishixin/Article/program/Java/hx/201311/26993

㈤ 急求:在JavaMail中,如何获取messages中的所有“未读”的邮件;通过uid能实现么具体是如何实现的呢

pop3由于本身不提供Flag的功能,所以一般来说没有办法判断通过pop3得到的message是否已读

但是有些服务商会在header里面加入message是否已读的信息
可以尝试用message.getHeader(String name)得到header的信息,比如用
message.getHeader("Status")
或许可以得到是否已读的信息(或许而已,因为这条语句成功与否取决于服务商是否加入该信息,以及使用的名字是否为"Status")
如果需要查看所有的header来判断这个服务商是否加入了message的状态信息,可以用
message.getAllHeaders() (返回的是Enumeration<Header>)
来获取所有的header然后一个个检查,如果里面没有的话,就没有办法了.

********************************************************

imap提供Flag,可以用
message.getFlags().getSystemFlags();
得到 Flag[], 然后去看其是否不为空,并且包括Flag.SEEN ,如果是,则为已读,反之则未读.

例如下面这个method可以返回message已读的状态 (true=已读,false=未读):

需要的imports:
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Flags.Flag;

代码:
private boolean isRead(Message message)
throws MessagingException {
Flag[] flags = message.getFlags().getSystemFlags();
for (Flag f : flags) {
if (f.equals(Flag.SEEN))
return true;
}
return false;
}

希望这些可以帮到你

㈥ javamail异常

一般情况,为了保障用户邮箱的安全,QQ邮箱设置了POP3/SMTP的开关。系统缺省设置是“关闭”,在用户需要POP3/SMTP功能时请“开启”。关闭POP3/SMTP后,您将只能接受邮件,不能发送邮件。

如果不是因为设置问题,试试QQ重新更改下登录密码。这时邮箱密码需要重新设置。

如果重设后没有用,可以考虑过几天试试,有可能QQ的邮件服务器认为你发的邮件为垃圾邮件。网上搜索的答案中,目前没有个定论,但是在QQ邮箱中,这种情况也是多见的。

阅读全文

与javamail设置pop3相关的资料

热点内容
要在电脑上写文件路径 浏览:689
dotaimba那个版本好玩 浏览:339
机房怎么不用u盘传文件 浏览:858
编程的美表现在哪些方面 浏览:240
win10如何显示工具栏 浏览:914
星瑞如何手机app远程关闭车辆 浏览:802
农金app怎么改信息 浏览:154
联通有哪些软件不用网络的 浏览:261
编程数据库英文叫什么 浏览:587
2016苹果游戏app排行榜 浏览:866
原子随身听支持哪些app 浏览:660
微信卖的沃颜面膜好吗 浏览:845
linuxnslookup反向解析 浏览:725
lumia1320能升级win10 浏览:482
php数据类型哪个不是标量类型 浏览:66
u盘启动盘文件bootini 浏览:552
ai绘制胶卷的图文教程 浏览:806
qq群文件夹删除 浏览:69
同花顺app怎么恢复默认设置 浏览:895
wpslinux命令 浏览:231

友情链接