㈠ java发邮件的几种方式
下面给你介绍3种发送邮件的方式:
1:使用JavaMail发送邮件
㈡ Java发送邮件
本地要 有smtp服务器,才可以测试 。。。。。。。。。。。。。~
~
~
~~~~~~~~~~~~~~~~~~~~~~~~
㈢ javamail如何判断邮件状态
pop3服务器是不支持此做法的,
你用Foxmail收邮件(保留备份在服务器上),然后再用邮件服务器自带的web收邮件,最后用OE收邮件,
我以前处理这一问题的做法供你参考参考:
收邮件时把邮件的唯一的UID字符串取出,并保存到web服务器的一个文本文件中,
这样就可以实现通过判断pop3服务器上的每一邮件的UID
是否已存在于文本文件中来确定是否为新邮件了.
㈣ java 代码发邮件怎么添加附件
实现java发送邮件的过程大体有以下几步:
准备一个properties文件,该文件中存放SMTP服务器地址等参数。
利用properties创建一个Session对象
利用Session创建Message对象,然后设置邮件主题和正文
利用Transport对象发送邮件
需要的jar有2个:activation.jar和mail.jar发送附件,需要用到Multipart对象。
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;
importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.activation.FileDataSource;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
importjavax.mail.internet.MimeUtility;
{
privateMimeMessagemessage;
privateSessionsession;
privateTransporttransport;
privateStringmailHost="";
privateStringsender_username="";
privateStringsender_password="";
privatePropertiesproperties=newProperties();
/*
*初始化方法
*/
publicJavaMailWithAttachment(booleandebug){
InputStreamin=JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties");
try{
properties.load(in);
this.mailHost=properties.getProperty("mail.smtp.host");
this.sender_username=properties.getProperty("mail.sender.username");
this.sender_password=properties.getProperty("mail.sender.password");
}catch(IOExceptione){
e.printStackTrace();
}
session=Session.getInstance(properties);
session.setDebug(debug);//开启后有调试信息
message=newMimeMessage(session);
}
/**
*发送邮件
*
*@paramsubject
*邮件主题
*@paramsendHtml
*邮件内容
*@paramreceiveUser
*收件人地址
*@paramattachment
*附件
*/
publicvoiddoSendHtmlEmail(Stringsubject,StringsendHtml,StringreceiveUser,Fileattachment){
try{
//发件人
InternetAddressfrom=newInternetAddress(sender_username);
message.setFrom(from);
//收件人
InternetAddressto=newInternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO,to);
//邮件主题
message.setSubject(subject);
//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipartmultipart=newMimeMultipart();
//添加邮件正文
BodyPartcontentPart=newMimeBodyPart();
contentPart.setContent(sendHtml,"text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
//添加附件的内容
if(attachment!=null){
BodyPartattachmentBodyPart=newMimeBodyPart();
DataSourcesource=newFileDataSource(attachment);
attachmentBodyPart.setDataHandler(newDataHandler(source));
//网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
//这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
//sun.misc.BASE64Encoderenc=newsun.misc.BASE64Encoder();
//messageBodyPart.setFileName("=?GBK?B?"+enc.encode(attachment.getName().getBytes())+"?=");
//MimeUtility.encodeWord可以避免文件名乱码
attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
//将multipart对象放到message中
message.setContent(multipart);
//保存邮件
message.saveChanges();
transport=session.getTransport("smtp");
//smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost,sender_username,sender_password);
//发送
transport.sendMessage(message,message.getAllRecipients());
System.out.println("sendsuccess!");
}catch(Exceptione){
e.printStackTrace();
}finally{
if(transport!=null){
try{
transport.close();
}catch(MessagingExceptione){
e.printStackTrace();
}
}
}
}
publicstaticvoidmain(String[]args){
JavaMailWithAttachmentse=newJavaMailWithAttachment(true);
Fileaffix=newFile("c:\测试-test.txt");
se.doSendHtmlEmail("邮件主题","邮件内容","[email protected]",affix);//
}
}
㈤ 怎样用java实现邮件的发送
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.SocketException;
import java.rmi.UnknownHostException;
import java.util.StringTokenizer;
import sun.misc.BASE64Encoder;
public class Sender {
//private boolean debug = true;
BASE64Encoder encode=new BASE64Encoder();//用于加密后发送用户名和密码
static int dk=25;
private Socket socket;
public Sender(String server, int port) throws UnknownHostException,
IOException {
try {
socket = new Socket(server, dk);
} catch (SocketException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
//System.out.println("已经建立连接!");
}
}
// 注册到邮件服务器
public void helo(String server, BufferedReader in, BufferedWriter out)
throws IOException {
int result;
result = getResult(in);
// 连接上邮件服务后,服务器给出220应答
if (result != 220) {
throw new IOException("连接服务器失败");
}
result = sendServer("HELO " + server, in, out);
// HELO命令成功后返回250
if (result != 250) {
throw new IOException("注册邮件服务器失败!");
}
}
private int sendServer(String str, BufferedReader in, BufferedWriter out)
throws IOException {
out.write(str);
out.newLine();
out.flush();
/*
if (debug) {
System.out.println("已发送命令:" + str);
}
*/
return getResult(in);
}
public int getResult(BufferedReader in) {
String line = "";
try {
line = in.readLine();
/*
if (debug) {
System.out.println("服务器返回状态:" + line);
}
*/
} catch (Exception e) {
e.printStackTrace();
}
// 从服务器返回消息中读出状态码,将其转换成整数返回
StringTokenizer st = new StringTokenizer(line, " ");
return Integer.parseInt(st.nextToken());
}
public void authLogin(MailMessage message, BufferedReader in,
BufferedWriter out) throws IOException {
int result;
result = sendServer("AUTH LOGIN", in, out);
if (result != 334) {
throw new IOException("用户验证失败!");
}
result=sendServer(encode.encode(message.getUser().getBytes()),in,out);
//System.out.println("用户名: "+encode.encode(message.getUser().getBytes()));
if (result != 334) {
throw new IOException("用户名错误!");
}
result=sendServer(encode.encode(message.getPassword().getBytes()),in,out);
//result=sendServer(message.getPassword(),in,out);
//System.out.println("密码: "+encode.encode(message.getPassword().getBytes()));
if (result != 235) {
throw new IOException("验证失败!");
}
}
// 开始发送消息,邮件源地址
public void mailfrom(String source, BufferedReader in, BufferedWriter out)
throws IOException {
int result;
result = sendServer("MAIL FROM:<" + source + ">", in, out);
if (result != 250) {
throw new IOException("指定源地址错误");
}
}
// 设置邮件收件人
public void rcpt(String touchman, BufferedReader in, BufferedWriter out)
throws IOException {
int result;
result = sendServer("RCPT TO:<" + touchman + ">", in, out);
if (result != 250) {
throw new IOException("指定目的地址错误!");
}
}
// 邮件体
public void data(String from, String to, String subject, String content,
BufferedReader in, BufferedWriter out) throws IOException {
int result;
result = sendServer("DATA", in, out);
// 输入DATA回车后,若收到354应答后,继续输入邮件内容
if (result != 354) {
throw new IOException("不能发送数据");
}
out.write("From: " + from);
out.newLine();
out.write("To: " + to);
out.newLine();
out.write("Subject: " + subject);
out.newLine();
out.newLine();
out.write(content);
out.newLine();
// 句号加回车结束邮件内容输入
result = sendServer(".", in, out);
//System.out.println(result);
if (result != 250) {
throw new IOException("发送数据错误");
}
}
// 退出
public void quit(BufferedReader in, BufferedWriter out) throws IOException {
int result;
result = sendServer("QUIT", in, out);
if (result != 221) {
throw new IOException("未能正确退出");
}
}
// 发送邮件主程序
public boolean sendMail(MailMessage message, String server) {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
helo(server, in, out);// HELO命令
authLogin(message, in, out);// AUTH LOGIN命令
mailfrom(message.getFrom(), in, out);// MAIL FROM
rcpt(message.getTo(), in, out);// RCPT
data(message.getDatafrom(), message.getDatato(),
message.getSubject(), message.getContent(), in, out);// DATA
quit(in, out);// QUIT
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
再写一个MailMessage.java,set/get方法即可。
㈥ javamail 回复邮件代码
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
/**
* <p>Title: java mail</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author petehero
* @version 1.0
*/
class SendMail
{
/**
* Logger for this class
*/
private static String server = "smtp.163.com";//smtp主机名。
private static String from = "[email protected]";//发送方邮件地址
private static String pw = "XXXXXX";//发送方邮件密码。
private static String to = "[email protected]"; //接收方邮件地址
static String subject="hello";
/*BodyPart bp = new MimeBodyPart();
Multipart mp = new MimeMultipart();
DataSource source = new FileDataSource("a.jpg");//附件
*/
static String mailContent="你好!\n\n"+"\t邮件正文test\n\n";//邮件正文
public static void send()
{
try
{
Properties props = new Properties();
Session sendMailSession;
Store store;
Transport transport;
props.put("mail.smtp.auth","true");
props.put("mail.smtp.host",server);
props.put("mail.smtp.user",from);
props.put("mail.smtp.password",pw);
//PopupAuthenticator popA=new PopupAuthenticator();
//PasswordAuthentication pop = popA.performCheck(from, pw);
//sendMailSession = Session.getInstance(props,popA);//填写用户名及密码
sendMailSession = Session.getInstance(props,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication() //邮件安全认证。
{
return new PasswordAuthentication(from, pw);
}
});
Message newMessage = new MimeMessage(sendMailSession);
newMessage.setFrom(new InternetAddress(from));
newMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
newMessage.setSubject(subject);
newMessage.setSentDate(new Date());
/*
bp.setText("bptext");
mp.addBodyPart(bp);
bp = new MimeBodyPart();
bp.setDataHandler(new DataHandler(source));
bp.setFileName("141.txt");
mp.addBodyPart(bp);
newMessage.setContent(mp);
*/
mailContent+=new Date().toLocaleString();
newMessage.setText(mailContent);
transport = sendMailSession.getTransport("smtp");
//System.out.println("Sending...");
//transport
Transport.send(newMessage);
//Transport.send(newMessage );
//System.out.println(server+from+pw+to);
}
catch (MessagingException ex)
{
}
}
// public static void main(String[] args)
// {
//
//// for(int i=0;i<args.length;i++)
//// {
//// System.out.println(args[i]);
//// }
//
// from=args[0].trim();
////
// pw=args[1].trim();
////
// SendMail sml = new SendMail();
// sml.send();
//// String a=SendMail.mailSend("hello","world");
//// System.out.println(a);
// }
static String mailSend(String t_to,String t_subject,String t_text)
{ String state="";
to=t_to;
subject=t_subject;
mailContent=t_text+"\n\n";
SendMail sml = new SendMail();
sml.send();
state="Successful";
return state;
}
/* public class PopupAuthenticator extends Authenticator{
String username=null;
String password=null;
public PopupAuthenticator(){}
public PasswordAuthentication performCheck(String user,String pass){
username = user;
password = pass;
return getPasswordAuthentication();
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}*/
}
㈦ javamail怎么删除指定邮件
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.AndTerm;
import javax.mail.search.FromStringTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
/**
* 使用 java.mail.search 包中的 SearchTerm 类
* 在接收邮件时进行组合搜索、过滤
* @author haolloyin
*/
public class SearchMails {
public static void main(String[] args) throws Exception {
// 连接pop3服务器的主机名、协议、用户名、密码
String pop3Server = "pop3.126.com";
String protocol = "pop3";
String user = "testhao";
String pwd = "123456";
// 创建一个有具体连接信息的Properties对象
Properties props = new Properties();
props.setProperty("mail.store.protocol", protocol);
props.setProperty("mail.pop3.host", pop3Server);
// 使用Properties对象获得Session对象
Session session = Session.getInstance(props);
session.setDebug(true);
// 利用Session对象获得Store对象,并连接pop3服务器
Store store = session.getStore();
store.connect(pop3Server, user, pwd);
// 获得邮箱内的邮件夹Folder对象,以"读-写"打开
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_WRITE);
// 搜索发件人为 [email protected] 和主题为"测试1"的邮件
SearchTerm st = new AndTerm(
new FromStringTerm("[email protected]"),
new SubjectTerm("测试1"));
// // 获得邮件夹Folder内的所有邮件Message对象
// Message [] messages = folder.getMessages();
// 不是像上面那样直接返回所有邮件,而是使用Folder.search()方法
Message [] messages = folder.search(st);
int mailCounts = messages.length;
System.out.println("搜索过滤到" + mailCounts + " 封符合条件的邮件!");
for(int i = 0; i < mailCounts; i++) {
String subject = messages[i].getSubject();
String from = (messages[i].getFrom()[0]).toString();
System.out.println("第 " + (i+1) + "封邮件的主题:" + subject);
System.out.println("第 " + (i+1) + "封邮件的发件人地址:" + from);
System.out.println("是否删除该邮件(yes/no)?:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
if("yes".equalsIgnoreCase(input)) {
// 直接输出到控制台中
// messages[i].writeTo(System.out);
// 设置删除标记,一定要记得调用saveChanges()方法
messages[i].setFlag(Flags.Flag.DELETED, true);
messages[i].saveChanges();
System.out.println("成功设置了删除标记!");
}
}
// 关闭连接时设置了删除标记的邮件才会被真正删除,相当于"QUIT"命令
folder.close(false);
store.close();
}
}
㈧ java 发送邮件
要两个java文件 还有一个mail.jar是不是只能用javamail谁也不敢说
第一个:
public class Constant {
public static final String mailAddress ="用户名@163.com";
public static final String mailCount ="用户名";
public static final String mailPassword ="密码";
public static final String mailServer ="smtp.163.com";
//pukeyouxintest,
}
第二个:
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
/**
* 发送简单邮件
* @param str_from:发件人地址
* @param str_to:收件人地址
* @param str_title:邮件标题
* @param str_content:邮件正文
*/
public static void send(String str_from,String str_to,String str_title,String str_content) {
// str_content="<a href='www.163.com'>html元素</a>"; //for testing send html mail!
try {
//建立邮件会话
Properties props=new Properties(); //用来在一个文件中存储键-值对的,其中键和值是用等号分隔的,
//存储发送邮件服务器的信息
props.put("mail.smtp.host",Constant.mailServer);
//同时通过验证
props.put("mail.smtp.auth","true");
//根据属性新建一个邮件会话
Session s=Session.getInstance(props);
s.setDebug(true); //有他会打印一些调试信息。
//由邮件会话新建一个消息对象
MimeMessage message=new MimeMessage(s);
//设置邮件
InternetAddress from= new InternetAddress(str_from); //[email protected]
message.setFrom(from); //设置发件人的地址
//
// //设置收件人,并设置其接收类型为TO
InternetAddress to=new InternetAddress(str_to); //[email protected]
message.setRecipient(Message.RecipientType.TO, to);
//设置标题
message.setSubject(str_title); //java学习
//设置信件内容
// message.setText(str_content); //发送文本邮件 //你好吗?
message.setContent(str_content, "text/html;charset=gbk"); //发送HTML邮件 //<b>你好</b><br><p>大家好</p>
//设置发信时间
message.setSentDate(new Date());
//存储邮件信息
message.saveChanges();
//发送邮件
Transport transport=s.getTransport("smtp");
//以smtp方式登录邮箱,第一个参数是发送邮件用的邮件服务器SMTP地址,第二个参数为用户名,第三个参数为密码
transport.connect(Constant.mailServer,Constant.mailCount,Constant.mailPassword);
//发送邮件,其中第二个参数是所有已设好的收件人地址
transport.sendMessage(message,message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//测试用的,你吧你想写的内容写上去就行
send(Constant.mailAddress,"收件人邮箱","标题","<b>内容</b>");
}
}
然后把mail.jar导入,就可以了,我用的是163 的,其他的吧相应的服务器改一下就行了
㈨ 如何用java实现发邮件功能,并有几点注意事项
packagecom.victor;
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;
importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.activation.FileDataSource;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
importjavax.mail.internet.MimeUtility;
{
privateMimeMessagemessage;
privateSessionsession;
privateTransporttransport;
privateStringmailHost="";
privateStringsender_username="";
privateStringsender_password="";
privatePropertiesproperties=newProperties();
/*
*初始化方法
*/
publicJavaMailWithAttachment(booleandebug){
InputStreamin=JavaMailWithAttachment.class.getResourceAsStream("/MailServer.properties");
try{
properties.load(in);
this.mailHost=properties.getProperty("mail.smtp.host");
this.sender_username=properties.getProperty("mail.sender.username");
this.sender_password=properties.getProperty("mail.sender.password");
}catch(IOExceptione){
e.printStackTrace();
}
session=Session.getInstance(properties);
session.setDebug(debug);//开启后有调试信息
message=newMimeMessage(session);
}
/**
*发送邮件
*
*@paramsubject
*邮件主题
*@paramsendHtml
*邮件内容
*@paramreceiveUser
*收件人地址
*@paramattachment
*附件
*/
publicvoiddoSendHtmlEmail(Stringsubject,StringsendHtml,StringreceiveUser,Fileattachment){
try{
//发件人
InternetAddressfrom=newInternetAddress(sender_username);
message.setFrom(from);
//收件人
InternetAddressto=newInternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO,to);
//邮件主题
message.setSubject(subject);
//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipartmultipart=newMimeMultipart();
//添加邮件正文
BodyPartcontentPart=newMimeBodyPart();
contentPart.setContent(sendHtml,"text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
//添加附件的内容
if(attachment!=null){
BodyPartattachmentBodyPart=newMimeBodyPart();
DataSourcesource=newFileDataSource(attachment);
attachmentBodyPart.setDataHandler(newDataHandler(source));
//网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
//这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
//sun.misc.BASE64Encoderenc=newsun.misc.BASE64Encoder();
//messageBodyPart.setFileName("=?GBK?B?"+enc.encode(attachment.getName().getBytes())+"?=");
//MimeUtility.encodeWord可以避免文件名乱码
attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
multipart.addBodyPart(attachmentBodyPart);
}
//将multipart对象放到message中
message.setContent(multipart);
//保存邮件
message.saveChanges();
transport=session.getTransport("smtp");
//smtp验证,就是你用来发邮件的邮箱用户名密码
transport.connect(mailHost,sender_username,sender_password);
//发送
transport.sendMessage(message,message.getAllRecipients());
System.out.println("sendsuccess!");
}catch(Exceptione){
e.printStackTrace();
}finally{
if(transport!=null){
try{
transport.close();
}catch(MessagingExceptione){
e.printStackTrace();
}
}
}
}
publicstaticvoidmain(String[]args){
JavaMailWithAttachmentse=newJavaMailWithAttachment(true);
System.out.println(se);
Fileaffix=newFile("E:\测试-test.txt");
//Fileaffix=null;
se.doSendHtmlEmail("##","###","####@##.com",affix);//
}
}
注意点:1 jar可能有冲突,如果是demo可以直接应用mail.jar
如果是一个工程则要替换javaEE中的mail.jar包
2 关于properties配置文件的地址问题
Class.getResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从
ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。
㈩ 怎么用JAVA实现邮件发送
用java mail 库