javamail完整的发送邮件实例

package cn.test;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;

import javax.mail.Message;

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;

import javax.mail.internet.MimeUtility;

/*

发送邮件代码

其他知识备注:

Mx和A记录(配置邮件服务器相关知识)

Mx:在dns上配置邮件服务器的域名和地址;作用为了让其他邮件服务器找到自己的服务器; A:在dns上配置邮件服务器的域名和地址;作用是为了让邮件服务器转发邮件时,不需要用户名和密码验证;

*/

public class SendMail {

public static void main(String[] args) throws Exception {

//MimeMessage在创建时需要指定一个session;而这个session通过Properties获得

//我们怎么配置属性里的字段呢?查找javamail规范JavaMail specification ; //jndi可以把session存到tomcat中;要使用jndi请查看tomcat documents JNDI Session Properties prop = new Properties();

prop.setProperty("mail.host", "");//搜狐专门有一个smtp的发送邮件服务器地址

prop.setProperty("mail.transport.protocol", "smtp");

prop.setProperty("mail.smtp.auth", "true");

prop.setProperty("mail.from", "xxx@sohu.com");

prop.setProperty("mail.user", "xxx@sohu.com");

// 1.创建session

Session session = Session.getInstance(prop);

session.setDebug(true);// 打开调试过程

// 2.通过session得到transport对象

Transport ts = session.getTransport();

// 3.连上邮件服务器 用自己的帐号密码登录到发送服务器

ts.connect(prop.getProperty("mail.host"),

prop.getProperty("mail.user"), "******");

// 4.创建邮件

Message message = makeMessage(session);

// 5.发送邮件

ts.sendMessage(message, message.getAllRecipients());

ts.close();

}

/*

* 一个复杂的邮件

*/

private static Message makeMessage(Session session) throws Exception { MimeMessage message = new MimeMessage(session);

// 设置邮件的基本信息

message.setFrom(new InternetAddress("xxx@sohu.com"));

//这里接收地址也设成自己

message.setRecipient(Message.RecipientType.TO, new

InternetAddress(

"yyy@sina.com"));

message.setSubject("测试");

// 正文

MimeBodyPart text = new MimeBodyPart();

text.setContent("xxx这是女的xxxx<br/><img src='cid:aaa.jpg'>", "text/html;charset=UTF-8");

// 图片

MimeBodyPart image = new MimeBodyPart();

image.setDataHandler(new DataHandler(new

FileDataSource("src\\1.jpg")));

image.setContentID("aaa.jpg");

// 附件1

MimeBodyPart attach = new MimeBodyPart();

DataHandler dh = new DataHandler(new FileDataSource("src\\2.jpg")); attach.setDataHandler(dh);

attach.setFileName(dh.getName());

// 附件2

MimeBodyPart attach2 = new MimeBodyPart();

DataHandler dh2 = new DataHandler(new FileDataSource("src\\菜鸟.zip"));

attach2.setDataHandler(dh2);

//解决附件乱码

attach2.setFileName(MimeUtility.encodeText(dh2.getName()));

// 描述关系:正文和图片

MimeMultipart mp1 = new MimeMultipart();

mp1.addBodyPart(text);

mp1.addBodyPart(image);

mp1.setSubType("related");

// 描述关系:正文和附件

MimeMultipart mp2 = new MimeMultipart();

mp2.addBodyPart(attach);

mp2.addBodyPart(attach2);

//mp1包装成一个MimeBodyPart;然后和mp2建立关系

MimeBodyPart content = new MimeBodyPart(); // 代表正文的bodypart content.setContent(mp1);

mp2.addBodyPart(content);

mp2.setSubType("mixed");

message.setContent(mp2);

message.saveChanges();

// message.writeTo(new FileOutputStream("c:\\3.eml"));

return message;

/*

* 简单的邮件 MimeMessage message = new MimeMessage(session); * message.setFrom(new InternetAddress("itcast1111@sohu.com")); * message.setRecipient(Message.RecipientType.TO, new

InternetAddress

* * ("itcast1111@sohu.com")); message.setSubject("test"); * message.setContent("aaa", "text/html");

*

* return message;

*/

}

}

 

第二篇:javamail 发送验证邮件(jspservlet实例源码)

javamail 发送验证邮件(jsp/servlet实例源码)

● 发送email:包括文本邮件、html邮件、带附件的邮件、smtp验证 ● 接收email:pop3远程连接、收取不同mime的邮件、处理附件

首先需要配置环境。需要mail.jar和activation.jar两个包。地址在上,很容易找到。放到classpath中,比如我的是这样. e:\tomcat5\common\lib\activation.jar e:\tomcat5\common\lib\mail.jar e: \tomcat5\common\lib\mailapi.jar e:\tomcat5\common\lib\ e:\jdk1.5\lib\dt.jar e:\jdk1.5\lib\tool.jar e:\jdk1.5\lib\ e:\jdk1.5\bin\ e:\jdk1.5。

--------------------------------------------------------------------------------

例子一、javamail.jsp 发送验证邮件源代码

< page language=" java" contenttype=" text/html charset=gbk" pageencoding=" gbk" >

<

//set chinese char

//homepage:

request.setcharacterencoding(" gbk" )

response.setcharacterencoding(" gbk" )

response.setcontenttype(" text/html 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 = " "

string user = " username"

string password = " xxxxx"

string contenttype=" text/html charset=gbk"

private class authenticator extends javax.mail.authenticator

{

public passwordauthentication getpasswordauthentication()

{

string un = user

string pw = password

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 = false

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> " + contents 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 源代码

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=" "

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(" " ) //指定要使用的邮件服务器

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:

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> < /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())+" ?=" )

//比如说有一个邮件帐号: smtpuser xxx.com

//pop3_host_name和smtp_host_name分别是这邮件地址的pop3和smtp服务器dns

//则smtp_auth_user =" smtpuser" smtp_auth_pwd就是该帐号的密码 private final string pop3_host_name = " "

private final string smtp_host_name = " "

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

}/

}

--------------------------------------------------------------------------------

sendmailusingauthentication.java 源代码,引用这个java bean发送认证email例子 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 ute it as follows

sendmailusingauthentication authprog = new sendmailusingauthentication() /

public class sendmailusingauthentication

{

private static final string smtp_host_name = " "

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 = " user 126.com"

// add list of email address to who email needs to be sent to

private static final string[] emaillist = {" username 126.com" " xxxx 126.com" }

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) }

}

}

相关推荐