本文实例讲述了html">JavaMail实现发送超文本(html)格式邮件的方法。分享给大家供大家参考。具体如下:
附件以超文本形式,很常用,与普通的邮件,只是查了一些设置,只有处理方式有些细微的差别
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
<%@ page contentType= "text/html;charset=GBK" %> <%@ page import = "java.util.*" %> <%@ page import = "javax.mail.*" %> <%@ page import = "javax.mail.internet.*" %> <%@ page import = "javax.activation.*" %> <% try { request.setCharacterEncoding( "GBK" ); String from=request.getParameter( "from" ); String to=request.getParameter( "to" ); String subject=request.getParameter( "subject" ); String messageText=request.getParameter( "content" ); String password=request.getParameter( "password" ); //****如果是在Internet上发送电子邮件, 使用这段代码自动生成SMTP的主机名称********/ //int n =from.indexOf('@'); //int m=from.length() ; //String mailserver ="smtp."+from.substring(n+1,m); String mailserver= "mrlx" ; //在局域网上发送电子邮件使用这句代码指定SMTP服务器 Properties prop = new Properties(); prop.put( "mail.smtp.host" ,mailserver); prop.put( "mail.smtp.auth" , "true" ); Session sess =Session.getInstance(prop); sess.setDebug( true ); MimeMessage message= new MimeMessage(sess); //给消息对象设置收件人、发件人、主题、发信时间 InternetAddress mail_from = new InternetAddress(from); message.setFrom(mail_from); InternetAddress mail_to = new InternetAddress(to); message.setRecipient(Message.RecipientType.TO,mail_to); message.setSubject(subject); message.setSentDate( new Date()); Multipart mul= new MimeMultipart(); //新建一个MimeMultipart对象来存放多个BodyPart对象 BodyPart mdp= new MimeBodyPart(); //新建一个存放信件内容的BodyPart对象 mdp.setContent(messageText, "text/html;charset=GBK" ); mul.addBodyPart(mdp); //将含有信件内容的BodyPart加入到MimeMulitipart对象中 message.setContent(mul); //把mul作为消息对象的内容 message.saveChanges(); Transport transport = sess.getTransport( "smtp" ); //以smtp方式登陆邮箱,第1个参数是发送邮件用的邮件服务器SMTP地址, //第2个参数为用户名,第3个参数为密码 transport.connect(mailserver,from,password); transport.sendMessage(message,message.getAllRecipients()); transport.close(); out.println( "<script language='javascript'>alert('邮件已发送!');window.location.href='index.jsp';</script>" ); } catch (Exception e){ System.out.println( "发送邮件产生的错误:" +e.getMessage()); out.println( "<script language='javascript'>alert('邮件发送失败!');window.location.href='index.jsp';</script>" ); } %> |
希望本文所述对大家的java程序设计有所帮助。