例子二、用Servlet来发送邮件 ,PostMail.java 源代码
package mail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
/*
* 创建日期 2005-12-1
*
* 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=host;
}
public void setAccount(String user,String password)
{
this.user=user;
this.password=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验证
try
{
//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/html;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/html; charset=GBK" pageEncoding="GBK" %>
<%
//set Chinese Char
//homepage:jiarry.126.com
request.setCharacterEncoding("GBK");
response.setCharacterEncoding("GBK");
response.setContentType("text/html; charset=GBK");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>电子邮件</title>
<script language="JavaScript">
<!--
function checkdata() {
var txt = document.forms[0].email.value;
if(txt.search("^//w+([-+.]//w+)*@//w+([-.]//w+)*//.//w+([-.]//w+)*$")!=0) {
alert("请输入正确电子邮件");
document.forms[0].email.select();
return false;
}
return true;
}
-->
</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("发件人邮件地址不正确");
return;
}
if(toemail.trim().length()>0 && !toemail.matches("^//w+([-+.]//w+)*@//w+([-.]//w+)*//.//w+([-.]//w+)*$")) {
out.print("收件人邮件地址不正确");
return;
}
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 源代码
package mail;
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())+"?=");
//比如说有一个邮件帐号: [email protected]
//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/html;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 multipart = new MimeMultipart();
MimeBodyPart bodyPart = new MimeBodyPart();
//内容
bodyPart.setText(body);
//Content-type
bodyPart.setContent(body, contentType);
multipart.addBodyPart(bodyPart);
for(int i=0; i<fileList.length; ++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=null;
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);
}
return mails;
}*/
}
package mail;
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 = "[email protected]";
// Add List of Email address to who email needs to be sent to
private static final String[] emailList = {"[email protected]", "[email protected]"};
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 = false;
//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.length; 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/html;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);
}
}
}
参考: Bromon原创 请尊重版权 怎样才算比较完整的Javamail操作指南?我想应该包括绝大多数基本的email操作,能够应付一般的应用。在本指南中打算囊括以下内容: ● 发送email:包括文本邮件、HTML邮件、带附件的邮件、SMTP验证 ● 接收email:pop3远程连接、收取不同MIME的邮件、处理附件 我想有了上述功能的介绍,应该可以应付很多email的相关应用了。所以请允许我给本文拟了一个比较狂妄的名字,这样才能保证收视率,:)。还是那句话,写这个post的原因就是没有在网上看到更全面的,你看过的话记得要告诉我。 下面的所有例子都经过实际测试,你可以说它写得不够OO,不够plugable,但是它的确是可以参考的。自从有了javamail,发垃圾邮件就方便多了。本文代码多说明少,这倒不是我偷懒,而是很多东西都涉及pop3等协议的规范,如果不了解这些规范的话,有的东西我实在不知道怎么跟你解释;如果了解的话,那我基本上就不用再解释。所以本着实用的原则就省略了,由兴趣的话自己去翻翻协议规范。 废话少说,首先需要配置环境。需要的包是mail.jar和activation.jar。高版本的J2SDK EE自带。地址嘛,再java.sun.com上搜索一下,很容易找到。放到classpath中就KO。 一、 邮件的发送 下面了弄个发邮件的Hello World,热热身:
程序很简单,但是它是不能运行的(倒)。除非你的机器上安装了一个SMTP服务器,而且你的机器还叫做bromon2k。写这么一段不能执行的程序不是为了找打,而是让各位对javamail有个基本印象,我就懒得改了。下面演示的是如何通过163、sohu等email服务商提供的免费邮箱来发邮件,基本操作和上面的一样,只是多一个SMTP验证而已:
这段程序好像也不需要解释了吧,把SMTP地址、帐号、密码等配置信息写到Properties里面,Java里面很多API都需要这么干,比如再程序中加入对代理服务器的支持等。 上面的程序修改一下服务器地址、帐号、密码就可以使用,非常简单。 如何发送一个HTML格式的Email呢?也很简单,再邮件正文中写入HTML代码,然后指定邮件的ContentType就OK,下面只给出关键代码:
下面是发送带有附件的email,稍微复杂一点,而且和前面的程序有一些不同,请仔细一点,同时需要一点IO的知识。相同的代码就不在列出,只写关键部分,谁都想偷懒不是?
这里的msg由两个MimeBodyPart构成,这个东西解释起来基本上比较难,如果不了解相关的规范就不太好解释,如果了解的话,我就不用解释了,这个这个………唉。 |
很多朋友都使用过JavaMail进行邮件发送,在邮件正文中的乱码容易解决。但邮件主题的乱码无论怎样转码总是显示一堆乱码。到底应该怎么处理呢?
JavaMail中的邮件主题需要进行BASE64编码,格式形如:
=?GB2312?B?xPq1xMPcwuvS0b6t1tjWw6Osx+u+ob/stcfCvKOssqLQ3rjEw9zC66Oh?=
所以,直接使用msg.setSubject("中文主题"),或者msg.setSubject("中文主题".getBytes("8859_1"), "GB2312"))都一样会出现乱码。在设置邮件主题前需要将主题字串的字节编码为BASE64格式,并添加编码头,示例代码如下:
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder(); msg.setSubject("=?GB2312?B?"+enc.encode(subject.getBytes())+"?=");
怎么样,现在中文可以正常显示了吧。
原文转自Java中文站