java邮件服务器 java mail 发邮件连接不上smtp服务器怎么办
今天给各位分享java邮件服务器的知识,其中也会对java mail 发邮件连接不上smtp服务器怎么办进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
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);//pukeyouxintest2@163.com
message.setFrom(from);//设置发件人的地址
//
////设置收件人,并设置其接收类型为TO
InternetAddress to=new InternetAddress(str_to);//pukeyouxintest3@163.com
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编写小型的局域网邮件发送
我给你提供一个我在项目里面实际使用的代码.
这是我基于一个网上的代码自己修改封装过来的.
你可以参考一下
/**
*
*@authorSglee
*
*/
publicclassSimpleMail{
privatestaticStringencode=null;
static{
if("\\".equals(File.separator)){
encode="GBK";
}else{
encode="UTF-8";
}
}
/**
*以文本格式发送邮件
*
*@parammailInfo
*@return
*/
publicstaticbooleansendTextMail(MailInfomailInfo){
for(inti=0;i<3;i++){
//判断是否需要身份认证
MyAuthenticatorauthenticator=null;
Propertiesproperties=mailInfo.getProperties();
if(mailInfo.isValidate()){
//如果需要身份认证,则创建一个密码验证器
authenticator=newMyAuthenticator(mailInfo.getUsername(),
mailInfo.getPassword());
}
//根据邮件会话属性和密码验证器构造一个发送邮件的session
SessionsendMailSession=Session.getDefaultInstance(properties,
authenticator);
if(mailInfo.isDebug()){
sendMailSession.setDebug(true);
}
try{
MessagemailMessage=newMimeMessage(sendMailSession);//根据session创建一个邮件消息
Addressfrom=newInternetAddress(mailInfo.getFromAddress());//创建邮件发送者地址
mailMessage.setFrom(from);//设置邮件消息的发送者
//Addressto=newInternetAddress(mailInfo.getToAddress());//
//创建邮件的接收者地址
//mailMessage.setRecipient(Message.RecipientType.TO,to);//
//设置邮件消息的接收者
mailMessage.setRecipients(Message.RecipientType.TO,
wrapAddress(mailInfo.getToAddress()));
//InternetAddressms=new
//InternetAddress(mailInfo.getMsAddress());
//mailMessage.setRecipient(Message.RecipientType.BCC,ms);//
//密送人
mailMessage.setRecipients(Message.RecipientType.BCC,
wrapAddress(mailInfo.getMsAddress()));
mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息的主题
mailMessage.setSentDate(newDate());//设置邮件消息发送的时间
//mailMessage.setText(mailInfo.getContent());//设置邮件消息的主要内容
//MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
MultipartmainPart=newMimeMultipart();
MimeBodyPartmessageBodyPart=newMimeBodyPart();//创建一个包含附件内容的MimeBodyPart
//设置HTML内容
messageBodyPart.setContent(mailInfo.getContent(),
"text/html;charset="+encode);
mainPart.addBodyPart(messageBodyPart);
//存在附件
String[]filePaths=mailInfo.getAttachFileNames();
if(filePaths!=null&&filePaths.length>0){
for(StringfilePath:filePaths){
messageBodyPart=newMimeBodyPart();
Filefile=newFile(filePath);
if(file.exists()){//附件存在磁盘中
FileDataSourcefds=newFileDataSource(file);//得到数据源
messageBodyPart
.setDataHandler(newDataHandler(fds));//得到附件本身并至入BodyPart
messageBodyPart.setFileName("=?"+encode+"?B?"
+file.getName());//得到文件名同样至入BodyPart
mainPart.addBodyPart(messageBodyPart);
}
}
}
//将MimeMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
Transport.send(mailMessage);//发送邮件
returntrue;
}catch(Exceptione){
e.printStackTrace();
try{
java.util.concurrent.TimeUnit.SECONDS.sleep(5);
}catch(Exceptione2){
e2.printStackTrace();
}
}
}
returnfalse;
}
/**
*将string[]包装成EmailAddress
*@parammailInfo
*@return
*@throwsAddressException
*/
privatestaticAddress[]wrapAddress(String[]adds)throwsAddressException{
//String[]adds=mailInfo.getToAddress();
if(adds==null||adds.length==0){
returnnull;
}
Address[]to=newAddress[adds.length];
for(inti=0;i<adds.length;i++){
to[i]=newInternetAddress(adds[i]);
}
returnto;
}
/**
*以HTML格式发送邮件
*
*@parammailInfo
*@return
*/
publicstaticbooleansendHtmlMail(MailInfomailInfo){
for(inti=0;i<3;i++){
//判断是否需要身份认证
MyAuthenticatorauthenticator=null;
Propertiesproperties=mailInfo.getProperties();
if(mailInfo.isValidate()){
//如果需要身份认证,则创建一个密码验证器
authenticator=newMyAuthenticator(mailInfo.getUsername(),
mailInfo.getPassword());
}
//根据邮件会话属性和密码验证器构造一个发送邮件的session
SessionsendMailSession=Session.getDefaultInstance(properties,
authenticator);
if(mailInfo.isDebug()){
sendMailSession.setDebug(true);
}
try{
MessagemailMessage=newMimeMessage(sendMailSession);//根据session创建一个邮件消息
Addressfrom=newInternetAddress(mailInfo.getFromAddress());//创建邮件发送者地址
mailMessage.setFrom(from);//设置邮件消息的发送者
//Addressto=newInternetAddress(mailInfo.getToAddress());//
//创建邮件的接收者地址
//mailMessage.setRecipient(Message.RecipientType.TO,to);//
//设置邮件消息的接收者
mailMessage.setRecipients(Message.RecipientType.TO,
wrapAddress(mailInfo.getToAddress()));
//InternetAddressms=new
//InternetAddress(mailInfo.getMsAddress());
//mailMessage.setRecipient(Message.RecipientType.BCC,ms);//
//密送人
mailMessage.setRecipients(Message.RecipientType.BCC,
wrapAddress(mailInfo.getMsAddress()));
mailMessage.setSubject(mailInfo.getSubject());//设置邮件消息的主题
mailMessage.setSentDate(newDate());//设置邮件消息发送的时间
//MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
MultipartmainPart=newMimeMultipart();
MimeBodyPartmessageBodyPart=newMimeBodyPart();//创建一个包含HTML内容的MimeBodyPart
//设置HTML内容
messageBodyPart.setContent(mailInfo.getContent(),
"text/html;charset="+encode);
mainPart.addBodyPart(messageBodyPart);
//存在附件
String[]filePaths=mailInfo.getAttachFileNames();
if(filePaths!=null&&filePaths.length>0){
sun.misc.BASE64Encoderenc=newsun.misc.BASE64Encoder();
for(StringfilePath:filePaths){
messageBodyPart=newMimeBodyPart();
Filefile=newFile(filePath);
if(file.exists()){//附件存在磁盘中
FileDataSourcefds=newFileDataSource(file);//得到数据源
messageBodyPart
.setDataHandler(newDataHandler(fds));//得到附件本身并至入BodyPart
messageBodyPart.setFileName("=?"+encode+"?B?"
+enc.encode(EmailFileNameConvert.changeFileName(file.getName()).getBytes())
+"?=");//得到文件名同样至入BodyPart
mainPart.addBodyPart(messageBodyPart);
}
}
}
//将MimeMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
Transport.send(mailMessage);//发送邮件
returntrue;
}catch(Exceptione){
e.printStackTrace();
try{
java.util.concurrent.TimeUnit.SECONDS.sleep(5);
}catch(Exceptione2){
e2.printStackTrace();
}
}
}
returnfalse;
}
}
/**
*封装邮件的基本信息
*
*@authorSglee
*
*/
publicclassMailInfoimplementsSerializable{
/**
*
*/
privatestaticfinallongserialVersionUID=-3937199642590071261L;
privateStringmailServerHost;//服务器ip
privateStringmailServerPort;//端口
privatelongtimeout;//超时时间
privateStringfromAddress;//发送者的邮件地址
privateString[]toAddress;//邮件接收者地址
privateString[]msAddress;//密送地址
privateStringusername;//登录邮件发送服务器的用户名
privateStringpassword;//登录邮件发送服务器的密码
privatebooleanvalidate=false;//是否需要身份验证
privateStringsubject;//邮件主题
privateStringcontent;//邮件内容
privateString[]attachFileNames;//附件的文件地址
privatebooleandebug;//调试模式
publicPropertiesgetProperties(){
Propertiesp=newProperties();
p.put("mail.smtp.host",this.mailServerHost);
p.put("mail.smtp.port",this.mailServerPort);
p.put("mail.smtp.auth",validate?"true":"false");
p.put("mail.smtp.timeout",this.timeout);
returnp;
}
publicStringgetMailServerHost(){
returnmailServerHost;
}
publicvoidsetMailServerHost(StringmailServerHost){
this.mailServerHost=mailServerHost;
}
publicStringgetMailServerPort(){
returnmailServerPort;
}
publicvoidsetMailServerPort(StringmailServerPort){
this.mailServerPort=mailServerPort;
}
publicStringgetFromAddress(){
returnfromAddress;
}
publicvoidsetFromAddress(StringfromAddress){
this.fromAddress=fromAddress;
}
publicString[]getToAddress(){
returntoAddress;
}
publicvoidsetToAddress(String[]toAddress){
this.toAddress=toAddress;
}
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
publicbooleanisValidate(){
returnvalidate;
}
publicvoidsetValidate(booleanvalidate){
this.validate=validate;
}
publicStringgetSubject(){
returnsubject;
}
publicvoidsetSubject(Stringsubject){
this.subject=subject;
}
publicStringgetContent(){
returncontent;
}
publicvoidsetContent(Stringcontent){
this.content=content;
}
publicString[]getAttachFileNames(){
returnattachFileNames;
}
publicvoidsetAttachFileNames(String[]attachFileNames){
this.attachFileNames=attachFileNames;
}
publicvoidsetMsAddress(String[]msAddress){
this.msAddress=msAddress;
}
publicString[]getMsAddress(){
returnmsAddress;
}
publicvoidsetDebug(booleandebug){
this.debug=debug;
}
publicbooleanisDebug(){
returndebug;
}
publicvoidsetTimeout(longtimeout){
this.timeout=timeout;
}
publiclonggetTimeout(){
returntimeout;
}
}
publicclassMyAuthenticatorextendsAuthenticator{
privateStringusername=null;
privateStringpassword=null;
publicMyAuthenticator(){
};
publicMyAuthenticator(Stringusername,Stringpassword){
this.username=username;
this.password=password;
}
protectedPasswordAuthenticationgetPasswordAuthentication(){
returnnewPasswordAuthentication(username,password);
}
}
注意一下:
Myeclipse自带的JavaEE5.jar和javamail会发生冲突
找到ME下的javeee包
D:\MyEclipse8.5\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.5.0.me201003231033\data\libraryset\EE_5\javaee.jar
用rar等解压工具解开javaee.jar,删除里面的javax\mail文件夹(可以先备份javaee.jar)
也即,以后都不能使用javaee.jar里面的邮件api发送邮件了.
java mail 发邮件连接不上smtp服务器怎么办
SMTP的是“Simple Mail Transfer Protocol”,即简单邮件传输协议。是一组用于从源地址到目的地址传输邮件的规范,通过控制邮件的中转方式。SMTP协议属于 TCP/IP协议簇,帮助每台计算机在发送或中转信件时找到下一个目的地。SMTP服务器就是遵循 SMTP协议的发送邮件服务器。SMTP认证,简单地说就是要求必须在提供了账户名和密码之后才可以登录 SMTP服务器,这就使得那些垃圾邮件的散播者无可乘之机。增加 SMTP认证的目的是为了使用户避免受到垃圾邮件的侵扰。
(1)可以尝试换一个邮箱服务器试一试.这个是可以连接上的
如果你还想了解更多这方面的信息,记得收藏关注本站。