javamail邮件发送实例 发送激活邮件失败,求助

博客分类:
转载自 bladecrazy最终编辑 bladecrazy● 发送email:包括文本邮件、HTML邮件、带附件的邮件、SMTP验证
● 接收email:pop3远程连接、收取不同MIME的邮件、处理附件
首先需要配置环境。需要mail.jar和activation.jar两个包。地址在java.sun.com上,很容易找到。放到classpath中,比如我的是这样.;E:\Tomcat5\common\lib\activation.E:\Tomcat5\common\lib\mail.E: \Tomcat5\common\lib\mailapi.E:\Tomcat5\common\lib\;E:\jdk1.5\lib\dt. E:\jdk1.5\lib\tool.E:\jdk1.5\lib\;E:\jdk1.5\bin\;E:\jdk1.5。
--------------------------------------------------------------------------------
例子一、javamail.jsp 发送验证邮件源代码
&%@ page language="java" contentType="text/ charset=GBK" pageEncoding="GBK" %&
&%
//set Chinese Char
//homepage:jiarry.126.com
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
response.setContentType("text/ charset=GBK");
%&
&%@ page import="javax.mail.*, javax.mail.internet.*,javax.activation.*,java.util.*,java.io.*;"%&
&html&
&head&
&title&JavaMail 电子邮件发送系统&/title&
&/head&
&body&
JavaMail 电子邮件发送系统
&br&本例子是用java mail来发送邮件的最简单的例子,认证才能正常发送邮件。
&form action="" method="post" OnSubmit=""&
收件人Email:&br /& &input type="text" name="recipients"&&br /&
发件人Mail:&br /& &input name="frommail" type="text" size="30" /&&br /&
邮件标题 &br /& &input name="subject" type="text" size="50" /&&br /&
内容:&br /& &textarea name="contents" cols="50" rows="10"&&/textarea&
&br /& &input type="submit" name="Submit" value="发送邮件" /&
&form&
&%!
String host = "smtp.126.com";
String user = "username";
String password = "xxxxx";
String contentType="text/ charset=gbk";
private class Authenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
String un =
String pw =
return new PasswordAuthentication(un, pw);
}
}
%&
&%
String touser = request.getParameter("recipients")!=null ? request.getParameter("recipients") : "";
out.print("&br&recipients:" + touser);
String fromuser = request.getParameter("frommail")!=null ? request.getParameter("frommail") : "";
out.print("&br&frommail:" + fromuser);
String subject = request.getParameter("subject")!=null ? request.getParameter("subject") : "";
out.print("&br&subject:" + subject);
String contents = request.getParameter("contents")!=null ? request.getParameter("contents") : "";
out.print("&br&contents:" + contents);
out.print("&br&");
try{
Properties props = new Properties();
props.put("mail.smtp.auth","true"); //是否验证
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", user);
props.put("mail.smtp.password",password);
boolean sessionDebug =
Authenticator auth = new Authenticator();
//Session mailSession = Session.getDefaultInstance(props, auth); //有时可能被拒绝
Session mailSession = Session.getInstance(props,auth); //用户验证;
//Session mailSession = Session.getInstance(props);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress( fromuser ));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress( touser ));
msg.setSubject( "邮件标题:" +subject);
//((MimeMessage)msg).setSubject(subject, "GBK"); //设置中文标题
msg.setSentDate(new Date());
String text = "javamail.jsp 发送认证邮件&b&测试&/b&。&hr&" +
msg.setContent(text, contentType);
Transport transport = mailSession.getTransport("smtp");
transport.connect(host,user,password);
transport.send( msg );
%&&p&你的邮件已发送,&a href="javascript:window.go(-1)"&请返回。&/&&/p&&%
}
catch(Exception m){out.println(m.toString());}%&
&/BODY&
&/HTML&
--------------------------------------------------------------------------------
例子二、用Servlet来发送邮件 ,PostMail.java 源代码
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
/*
* 创建日期
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
/**
* @author Administrator
*
* TODO 要更改此生成的类型注释的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
public class PostMail {
/*String mailform=""; String mailto="";String mailsubject="";String mailcontent="";*/
String host="smtp.126.com";
String user="username";
String password="xxxxx";
public void setHost(String host)
this.host=
& public void setAccount(String user,String password)
this.user=
this.password=
& public void send(String from,String to,String subject,String content)
Properties props = new Properties();
props.put("mail.smtp.host", host);//指定SMTP服务器
props.put("mail.smtp.auth", "true");//指定是否需要SMTP验证
//Session mailSession = Session.getDefaultInstance(props);//用这个有时被拒绝;
Session mailSession = Session.getInstance(props);
mailSession.setDebug(true);//是否在控制台显示debug信息
Message message=new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));//发件人
message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));//收件人&& //message.setSubject(subject);&
((MimeMessage)message).setSubject(subject, "GBK");
//得到中文标题for linux,windows下不用;&&&
// message.setSubject(subject);//邮件主题&&&
//内容类型Content-type
//普通文本为text/plain,html格式为text/html
message.setContent(content,"text/charset=GBK");
//message.setText("&html&&body&&h1&Java Mail,你好!&/body&&/html&");
message.setText(content);//邮件内容
message.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, user, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}catch(Exception e)
System.out.println(e);
& public static void main(String args[])
/*& PostMail sm=new PostMail();
&& sm.setHost("smtp.126.com");//指定要使用的邮件服务器
sm.setAccount("xxxxx","xxxxx");//指定帐号和密码
* @param String 发件人的地址
* @param String 收件人地址
* @param String 邮件标题
* @param String 邮件正文
调用PostMail.java的jsp文件:postmail.jsp源代码
&%@ page language="java" contentType="text/ charset=GBK" pageEncoding="GBK" %&
&%
//set Chinese Char
//homepage:jiarry.126.com
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
response.setContentType("text/ charset=GBK");
%&
&html&
&head&
&meta http-equiv="Content-Type" content="text/ charset=gb2312"&
&title&电子邮件&/title&
&script language="JavaScript"&
&!--
function checkdata() {
var txt& = document.forms[0].email.
if(txt.search("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")!=0) {
alert("请输入正确电子邮件");
document.forms[0].email.select();
}
--&
&/script&
&/head&
&body&
&p&
&%
java.util.Date date = new java.util.Date();
out.print(new java.util.Date());
out.print("&hr&");
%&
本例子是调用PostMail.java来发送认证的邮件,需要下载mail.jar和activation.jar,并设置classpath
&jsp:useBean id="mail" scope="page" class="mail.PostMail" /&
&form action="" method="post" OnSubmit="return checkdata()"&
&p&请输入发件人电子邮件:&input type="text" name="email"&
&p&请输入收件人电子邮件:&input type="text" name="toemail"&
&p&&input type="submit" value="发送"&
&form&
&%
String email ="",toemail="";
if(request.getParameter("email")!=null){
email =request.getParameter("email");
}
if(request.getParameter("toemail")!=null){
toemail =request.getParameter("toemail");
}
//if(email!=null)
if( email.trim().length()&0 && !email.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")) {
out.print("发件人邮件地址不正确");
}
if(toemail.trim().length()&0 && !toemail.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")) {
out.print("收件人邮件地址不正确");
if(email.trim().length()&0 && toemail.trim().length()&0){
try{
mail.send(email,toemail, "Test PostMail.java 中文", "&h1&Java Mail,你好 PostMail!&/h1&&br&&br&&b&Jiarry.126.com&/b&");
out.print("&font color='green'&邮件发送&/font&");
}catch(Exception e){
out.print( "&font color='red'&出错了&/font&");
out.print(e.getMessage());
System.out.print(e.getMessage());
}
}
%&
&/body&
&/html&
--------------------------------------------------------------------------------
其他java源代码:MailManager.java 源代码
import javax.mail.*;&
import javax.mail.internet.*;&
import java.util.*;
import javax.activation.*;
import java.io.*;
public class MailManager {
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
//比如说有一个邮件帐号:
//POP3_HOST_NAME和SMTP_HOST_NAME分别是这邮件地址的pop3和smtp服务器DNS
//则SMTP_AUTH_USER ="smtpuser", SMTP_AUTH_PWD就是该帐号的密码
private& final String POP3_HOST_NAME = "pop3.126.com";
private& final String SMTP_HOST_NAME = "smtp.126.com";
private& final String SMTP_AUTH_USER = "username";
private& final String SMTP_AUTH_PWD& = "xxxxxx";
private Authenticator auth = new Authenticator(){
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(SMTP_AUTH_USER, SMTP_AUTH_PWD);
}
};
public void sendMail(String toAddr, String subject,
String body, String fromAddr, String contentType) {
try {&
Properties props = new Properties();&
//指定SMTP服务器,邮件通过它来投递
props.put("mail.smtp.host", (String)SMTP_HOST_NAME);
props.put("mail.smtp.auth", (String)"true");&&
//Session session =Session.getDefaultInstance(props, auth);
Session session =Session.getInstance(props, auth); //
Message msg = new MimeMessage(session);&
//指定发信人
msg.setFrom(new InternetAddress(fromAddr));
&& //指定收件人
//InternetAddress[] tos = {new InternetAddress(toAddr)};&
//msg.setRecipients(Message.RecipientType.TO,tos);
//指定收件人,多人时用逗号分隔
InternetAddress[] tos =InternetAddress.parse(toAddr);&
msg.setRecipients(Message.RecipientType.TO,tos);
&& //标题//转码BASE64Encoder
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//msg.setSubject("=?GBK?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(new String(subject.getBytes("GBK"),"ISO8859-1"));
//msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(subject);
((MimeMessage)msg).setSubject(subject,"GBK");
//得到中文标题for linux,windows下不用;
//内容
msg.setText(body);
//发送时间
msg.setSentDate(new Date());
//内容类型Content-type
//普通文本为text/plain,html格式为text/charset=GBK
msg.setContent(body, contentType);
//发送
Transport.send(msg);&
} catch(Exception e){&
System.out.println(e);&
public void sendMailWithAttatchment(String toAddr, String subject, String body,
String fromAddr, String contentType, String []fileList) {
try {&
Properties props = new Properties();&
//指定SMTP服务器,邮件通过它来投递
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
&& Session session = Session.getDefaultInstance(props, auth);
//Session session = Session.getInstance(props, auth);//
SecurityManager security = System.getSecurityManager();
System.out.println("Security Manager" + security);
//Looking at your code it looks like you will see a null value for security.
//If the security is null use session.getInstance(props,auth)
//instead of session.getDefaultInstance(props,auth).
&& Message msg = new MimeMessage(session);&
//指定发信人
msg.setFrom(new InternetAddress(fromAddr));
//指定收件人
//InternetAddress[] tos = {new InternetAddress(toAddr)};&
//msg.setRecipients(Message.RecipientType.TO,tos);
//指定收件人,多人时用逗号分隔
InternetAddress[] tos =InternetAddress.parse(toAddr);&
msg.setRecipients(Message.RecipientType.TO,tos);
//标题//转码BASE64Encoder
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//msg.setSubject("=?GBK?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(new String(subject.getBytes("GBK"),"ISO8859-1"));
//msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(subject);
((MimeMessage)msg).setSubject(subject, "GBK");
//得到中文标题for linux,windows下不用;
//发送时间
//msg.setSentDate(new Date());
msg.setSentDate(new java.util.Date());
Multipart mutipart = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();
//内容
bodyPart.setText(body);
//Content-type
bodyPart.setContent(body, contentType);
multipart.addBodyPart(bodyPart);
for(int i=0; i&fileList. ++i) {
bodyPart = new MimeBodyPart();
File f = new File(fileList[i]);
DataSource source = new FileDataSource(f);
bodyPart.setDataHandler(new DataHandler(source));
bodyPart.setFileName(f.getName());
multipart.addBodyPart(bodyPart);
}
msg.setContent(multipart);
&& //发送
Transport.send(msg);&
} catch(Exception e){&
System.out.println(e);&
}
/*
public Mails getMails() {
Mails mails=
try {&
//Properties props = System.getProperties();
Properties props = new Properties();&&&
props.put("mail.pop3.host", SMTP_HOST_NAME);
props.put("mail.pop3.auth", "true");
&& Session session = Session.getDefaultInstance(props, auth);
Store store = session.getStore("pop3");
store.connect();
Folder inbox = store.getFolder("INBOX");
mails = new Mails(inbox);
store.close();
} catch(Exception e){
System.out.println(e);
--------------------------------------------------------------------------------
SendMailUsingAuthentication.java 源代码,引用这个java bean发送认证email例子
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
/*
To use this program, change values for the following three constants,
&&& SMTP_HOST_NAME -- Has your SMTP Host Name
SMTP_AUTH_USER -- Has your SMTP Authentication UserName
SMTP_AUTH_PWD& -- Has your SMTP Authentication Password
& Next change values for fields
& emailMsgTxt& -- Message Text for the Email
emailSubjectTxt& -- Subject for email
emailFromAddress -- Email Address whose name will appears as "from" address
& Next change value for "emailList".
This String array has List of all Email Addresses to Email Email needs to be sent to.
Next to run the program, execute it as follows,
& SendMailUsingAuthentication authProg = new SendMailUsingAuthentication();
public class SendMailUsingAuthentication
{
& private static final String SMTP_HOST_NAME = "smtp.126.com";
private static final String SMTP_AUTH_USER = "username";
private static final String SMTP_AUTH_PWD& = "******";
& private static final String emailMsgTxt&&&&& = "Online Order Confirmation Message. Also include the Tracking Number.中国人";
private static final String emailSubjectTxt& = "这里是标题,Java Mail test";
private static final String emailFromAddress = "";
& // Add List of Email address to who email needs to be sent to
private static final String[] emailList = {"", ""};
public static void main(String args[]) throws Exception
{
//SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
//smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
//smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
//System.out.println("Sucessfully Sent mail to All Users");
}
& public void postMail( String recipients[], String subject,
//public void postMail( String recipients, String subject,
String message , String from) throws MessagingException
{
boolean debug =
&&&& //Set the host smtp address
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
&&& Authenticator auth = new SMTPAuthenticator();
//Session session = Session.getDefaultInstance(props, auth); //有时可能被拒绝
Session session = Session.getInstance(props,auth);
session.setDebug(debug);
&&& // create a message
Message msg = new MimeMessage(session);
&&& // set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
&&& InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i & recipients. i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);
&& // msg.setRecipient(Message.RecipientType.TO,toemail);
// Setting the Subject and Content Type
//标题//转码BASE64Encoder
//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//msg.setSubject("=?GBK?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(new String(subject.getBytes("GBK"),"ISO8859-1"));
//msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
//msg.setSubject(subject);
((MimeMessage)msg).setSubject(subject, "GBK");
//得到中文标题for linux,windows下不用;
// msg.setSubject(subject);
msg.setContent(message, "text/charset=GBK");
//msg.setContent(message, "text/plain");
Transport.send(msg);
}
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private class SMTPAuthenticator extends javax.mail.Authenticator
{
&&& public PasswordAuthentication getPasswordAuthentication()
{
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
}
stevenjohn
浏览: 1059121 次
来自: 深圳
每次看你头像都看的荷尔蒙分泌失调
hollo 写道一直有这种感觉,盲目的跟风,确实有一些人为了潮 ...
博主,JNative怎么调用dll中的这种方法:
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'2349人阅读
javamail java.net.SocketException: Permission denied: connect
现象描述: javaee6环境下, 用javamail发送邮件时,报下列异常:
Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: smtp.sina.com, port: 25;
nested exception is:
java.net.SocketException: Permission denied: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1008)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:197)
at javax.mail.Service.connect(Service.java:233)
at javax.mail.Service.connect(Service.java:134)
at com.newland.mail.MailExample.main(MailExample.java:150)
解决方案:
1、关闭IPv6
2、设置IPv4优先选项
有两种设置方式:
方式一:java代码中添加:
System.setProperty("java.net.preferIPv4Stack" , "true");
方式二:java vm arguments添加:
-Djava.net.preferIPv4Stack=true
参考英文:
Specific Troubleshooting
AnyConnect
For AnyConnect-related issues, collect the Diagnostic AnyConnect Reporting (DART) logs as well as the Java console logs.
Cisco bug ID CSCuc55720, "IE crashes with Java 7 when 3.1.1 package is enabled on the ASA," was a known issue, where Internet Explorer crashed when a WebLaunch was performed and AnyConnect 3.1 was enabled on the headend. This bug
has been fixed.
You might encounter issues when you use some versions of AnyConnect and Java 7 with Java apps. For further information, see Cisco bug ID CSCue48916, "Java App(s) Break when using AnyConnect 3.1.00495 or 3.1.02026 & Java v7."
Issues with Java 7 and IPv6 Socket Calls
If AnyConnect does not connect even after you upgrade the Java Runtime Environment (JRE) to Java 7, or if a Java application is unable to connect over the VPN tunnel, review the Java console logs and look for these messages:
java.net.SocketException: Permission denied: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
These log entries indicate that the client/application makes IPv6 calls.
One solution for this issue is to disable IPv6 (if it is not in use) on the Ethernet adapter and the AnyConnect Virtual Adapter (VA):
A second solution is to configure Java to prefer IPv4 over IPv6. Set the system property 'java.net.preferIPv4Stack' to 'true' as shown in these examples:
Add code for the system property to the Java code (for Java applications written by the customer):
System.setProperty("java.net.preferIPv4Stack" , "true");
Add code for the system property from the command line:
-Djava.net.preferIPv4Stack=true
Set the environment variables _JPI_VM_OPTIONS and _JAVA_OPTIONS in order to include the system property:
-Djava.net.preferIPv4Stack=true
如果系统中开启了IPV6协议(比如window7),java网络编程经常会获取到IPv6的地址,这明显不是我们想要的结果,搜索发现很多蹩脚的做法是:禁止IPv6协议。其实查看官方文档有详细的说明:
java.net.preferIPv4Stack (default: false)
If IPv6 is available on the operating system the underlying native socket
will be an IPv6 socket. This allows Java(tm) applications to connect too, and
accept connections from, both IPv4 and IPv6 hosts.
If an application has a preference to only use IPv4 sockets then this
property can be set to true. The implication is that the application will not be
able to communicate with IPv6 hosts.
在实际的运用中有以下几种办法可以实现指定获取IPv4的地址:
1. 在java启动命令中增加一个属性配置:-Djava.net.preferIPv4Stack=true
123java -Djava.net.preferIPv4Stack=true -cp .;classes/ michael.net.TestInetAddress java -Djava.net.preferIPv6Addresses=true -cp .;classes/ michael.net.TestInetAddress2.在java程序里设置系统属性值如下:
packagemichael.net;
importjava.net.InetAddress;
@blog http://www.micmiu.com
publicclassTestInetAddress{
* @param args
publicstaticvoidmain(String[]args)throwsException{
注释指定系统属性值
System.setProperty("java.net.preferIPv4Stack", "true");
System.setProperty("java.net.preferIPv6Addresses", "true");
System.out.println("-------InetAddress.getLocalHost()");
InetAddressaddr=InetAddress.getLocalHost();
System.out.println("HostName
:= "+addr.getHostName());
System.out.println("HostAddress
:= "+addr.getHostAddress());
System.out.println("-------InetAddress.getByName(\"micmiu.com\")");
InetAddressaddr2=InetAddress.getByName("micmiu.com");
System.out.println("HostName
:= "+addr2.getHostName());
System.out.println("HostAddress
:= "+addr2.getHostAddress());
java.net.preferIPv4Stack=true 运行结果如下:
——-InetAddress.getLocalHost()
HostName := Michael-PC
HostAddress := 10.7.246.163
——-InetAddress.getByName(“micmiu.com”)
HostName := micmiu.com
HostAddress := 173.254.28.17
java.net.preferIPv6Addresses=true
运行结果如下:
——-InetAddress.getLocalHost()
HostName := Michael-PC
HostAddress := fe80:0:0:0:6518:85da:8690:16eb%13
——-InetAddress.getByName(“micmiu.com”)
HostName := micmiu.com
HostAddress := 173.254.28.17
3.tomcat Web容器
可在 catalina.bat 或者 catalina.sh 中增加如下环境变量即可:SET CATALINA_OPTS=-Djava.net.preferIPv4Stack=true
云服务商禁止了向邮件服务器的连接
防火墙规则
杀毒软件等安全软件禁用了邮件发信功能,解决办法,将java.exe添加到禁止发邮件的例外规则里
服务器的ip被邮件服务器拒绝,解决方法:向邮件服务提供商联系,请求列入白名单。}

我要回帖

更多关于 javamail发送邮件代码 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信