java邮件发送代码
t.base;
import java.util.*;
import javax.mail.*;
import .*;
import java.util.Date;
import javax.activation.*;
import java.io.*;
public class SendMail {
private MimeMessage mimeMsg; // MIME邮件对象
private Session session; // 邮件会话对象
private Properties props; // 系统属性
private boolean needAuth = false; // smtp是否需要认证
private String username ; // smtp认证用户名和密码
private String password ;
private Multipart mp; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
private String serverEmailBox;//服务器邮箱
/**
*
*/
/*public sendMail() {
setSmtpHost(getConfig.mailHost);// 如果没有指定邮件服务器,就从getConfig类中获取
createMimeMessage();
}*/
public SendMail(String smtp) {
setSmtpHost(smtp);
createMimeMessage();
}
/**
* @param hostName
* String
*/
public void setSmtpHost(String hostName) {
if (props == null)
props = System.getProperties(); // 获得系统属性对象
props.put("mail.smtp.host", hostName); // 设置SMTP主机
}
/**
* @return boolean
*/
public boolean createMimeMessage() {
try {
session = Session.getDefaultInstance(props, null); // 获得邮件会话对象
} catch (Exception e) {
System.err.println("获取邮件会话对象时发生错误!" + e);
return false;
}
try {
mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
mp = new MimeMultipart();
return true;
} catch (Exception e) {
System.err.println("创建MIME邮件对象失败!" + e);
return false;
}
}
/**
* @param need
* boolean
*/
public void setNeedAuth(boolean need) {
if (props == null)
props = System.getProperties();
if (need) {
props.put("mail.smtp.auth", "true");
} else {
props.put("mail.smtp.auth", "false");
}
}
/**
* @param name
* String
* @param pass
* String
*/
public void setNamePass(String name, String pass) {
username = name;
password = pass;
}
/**
* @param mailSubject
* String
* @return boolean
*/
public boolean setSubject(String mailSubject) {
try {
mimeMsg.setSubject(mailSubject);
return true;
} catch (Exception e) {
System.err.println("设置邮件主题发生错误!");
return false;
}
}
/**
* @param mailBody
* String
*/
public boolean setBody(String mailBody) {
try {
BodyPart bp = new MimeBodyPart();
bp.setContent("" + mailBody, "text/html;charset=GB2312");
mp.addBodyPart(bp);
return true;
} catch (Exception e) {
System.err.println("设置邮件正文时发生错误!" + e);
return false;
}
}
/**
* @param name
* String
* @param pass
* String
*/
public boolean addFileAffix(String filename) {
try {
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
return true;
} catch (Exception e) {
System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
return false;
}
}
/**
* @param name
* String
* @param pass
* String
*/
public boolean setFrom(String from) {
try {
mimeMsg.setFrom(new Address(from)); // 设置发信人
return true;
} catch (Exception e) {
return false;
}
}
/**
* @param name
* String
* @param pass
* String
*/
public boolean setTo(String to) {
if (to == null)
return false;
try {
mimeMsg.setRecipients(Message.RecipientType.TO, Address
.parse(to));
return true;
} catch (Exception e) {
return false;
}
}
/**
* @param name
* String
* @param pass
* String
*/
public boolean setCopyTo(String copyto) {
if (copyto == null)
return false;
try {
mimeMsg.setRecipients(Message.RecipientType.CC,
(Address[]) Address.parse(copyto));
return true;
} catch (Exception e) {
return false;
}
}
/**
* @param name
* String
* @param pass
* String
*/
public boolean sendout() {
try {
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
Session mailSession = Session.getInstance(props, null);
Transport transport = mailSession.getTransport("smtp");
transport.connect((String) props.get("mail.smtp.host"), username,
password);
transport.sendMessage(mimeMsg, mimeMsg
.getRecipients(Message.RecipientType.TO));
// transport.send(mimeMsg);
transport.close();
return true;
} catch (Exception e) {
System.err.println("邮件发送失败!" + e);
return false;
}
}
/**
* Just do it as this
*/
public void sendEmail(String title,String content,String cilentEmailAddr) {
//sendMail themail = new sendMail("");
setNeedAuth(true);
if (setSubject(title) == false)
return;
if (setBody(content) == false)
return;
if (setTo(cilentEmailAddr) == false)
return;
if (setFrom(serverEmailBox) == false)
return;
/*if (themail.addFileAffix("c:\测试附件.txt") == false)
return;*/
//themail.setNamePass("lihuiqiang1984", "010200673#");
if (sendout() == false)
return;
}
public void setPassword(String password) {
this.password = password;
}
public void setUsername(String username) {
this.username = username;
}
public void setServerEmailBox(String serverEmailBox) {
this.serverEmailBox = serverEmailBox;
}
}
用java写收发邮件的程序,求助,在线
主要类用到了 Session Messager Address Transport等,
代码如下:
public class MailUtils{ private static Properties p = System.getProperties(); /**获取Message对象*/ private static Message getMessage() throws Exception{ p.put("mail.smtp.host", ""); //新浪邮箱服务器 p.put("mail.smtp.username","发送人新浪邮箱地址"); p.put("mail.smtp.auth","true"); //发送人邮箱密码 p.put("mail.smtp.pswd","xxxxxxxx"); //获取Session对象 Session session = Session.getInstance(p, new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(p.getProperty("mail.smtp.username"), p.getProperty("mail.smtp.pswd")); } }); session.setDebug(true); //创建Message对象 Message message = new MimeMessage(session); message.setFrom(new Address(p.getProperty("mail.smtp.username"), "...getProperty("获取Session对象 Session session = Session.smtp;.parse("mail;);/.put(" message.setReplyTo(Address;); public static void sendHTML(String content) { Message message = getMessage(); /text//.username".setFrom(new Address(p.getInstance(p.smtp;/ } /.smtp; p:
public class MailUtils{ private static Properties p = System,"mail.pswd")).host"mail.getProperties(); session;smtp.put("设置收件人点击回复的时候回复地址 message.username" return message ;创建Message对象 Message message = new MimeMessage(session).smtp;发送人新浪邮箱地址";);设置邮件标题"**获取Message对象*/.setDebug(true); public static void sendText(String text) { Message message = getMessage(),可随意设置;收件人地址".put(" message;); /mail, new Address(" /, new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(p,".smtp; /).setContent(content.setRecipient(Message; //**发送文本格式的邮件*/)).smtp; message;mail; message;可以是发件人地址; Transport; private static Message getMessage() throws Exception{ p; } /true"/.send(message).sina;**发送html格式的邮件*/mail;);新浪邮箱服务器 p, ").smtp; /.put(".getProperty(".RecipientType; /发送人邮箱密码 p;)),
代码如下,也可不设置"/.username".TO;charset=utf-8"mail;;),"html; } })"设置发送人模式 TO代表主发送 message; Transport,"xxxxxxxx",也可以是其他".pswd", ".setText(text);发送者别名.getProperty(", p.send(message)主要类用到了 Session Messager Address Transport等;)).setSubject(".auth"
如何用java实现发送html格式的邮件
首先Java发送邮件需要用到JavaMail,先到Oracle官网上下载好最新版本的JavaMail(刚才看了一下,最新是1.5.3),把下载的这个jar文件放到classpath里(如果是Web项目,就放到WEB-INF/lib目录下。
JavaMail主要支持发送纯文本的和html格式的邮件。
发送html格式的邮件的一个例程如下:
?
?import?Address;
?import?.MimeMessage;
?import?.MimeUtility;
?import?javax.mail.Session;
?import?javax.mail.MessagingException;
import?javax.mail.Transport;
public?class?SendHtmlMail?{
?????public?static?void?sendMessage(String?smtpHost,
????????????????????????????????????String?from,?String?to,
????????????????????????????????????String?subject,?String?messageText)
?????????????throws?MessagingException,java.io.UnsupportedEncodingException?{
?????????//?Step?1:??Configure?the?mail?session
?????????System.out.println("Configuring?mail?session?for:?"?+?smtpHost);
?????????java.util.Properties?props?=?new?java.util.Properties();
?????????props.setProperty("mail.smtp.auth",?"true");//指定是否需要SMTP验证
?????????props.setProperty("mail.smtp.host",?smtpHost);//指定SMTP服务器
?????????props.put("mail.transport.protocol",?"smtp");
?????????Session?mailSession?=?Session.getDefaultInstance(props);
?????????mailSession.setDebug(true);//是否在控制台显示debug信息
?????????//?Step?2:??Construct?the?message
?????????System.out.println("Constructing?message?-??from="?+?from?+?"??to="?+?to);
?????????Address?fromAddress?=?new?Address(from);
?????????Address?toAddress?=?new?Address(to);
?????????MimeMessage?testMessage?=?new?MimeMessage(mailSession);
?????????testMessage.setFrom(fromAddress);
?????????testMessage.addRecipient(javax.mail.Message.RecipientType.TO,?toAddress);
?????????testMessage.setSentDate(new?java.util.Date());
?????????testMessage.setSubject(MimeUtility.encodeText(subject,"gb2312","B"));
????????testMessage.setContent(messageText,?"text/html;charset=gb2312");
?????????System.out.println("Message?constructed");
????????//?Step?3:??Now?send?the?message
?????????Transport?transport?=?mailSession.getTransport("smtp");
?????????transport.connect(smtpHost,?"webmaster",?"password");
?????????transport.sendMessage(testMessage,?testMessage.getAllRecipients());
?????????transport.close();
?????????System.out.println("Message?sent!");
?????}
?????public?static?void?main(String[]?args)?{
?????????String?smtpHost?=?"localhost";
?????????String?from?=?"webmaster@";
?????????String?to?=?"mfc42d@";
?????????String?subject?=?"html邮件测试";?//subject?javamail自动转码
?????????StringBuffer?theMessage?=?new?StringBuffer();
?????????theMessage.append("<h2><font?color=red>这倒霉孩子</font></h2>");
?????????theMessage.append("<hr>");
?????????theMessage.append("<i>年年失望年年望</i>");
?????????try?{
????????????SendHtmlMail.sendMessage(smtpHost,?from,?to,?subject,?theMessage.toString());
?????????}
?????????catch?(javax.mail.MessagingException?exc)?{
?????????????exc.printStackTrace();
?????????}
?????????catch?(java.io.UnsupportedEncodingException?exc)?{
?????????????exc.printStackTrace();
?????????}
?????}
?}
JavaMail是封装了很多邮件操作的,所以使用起来不很困难,建议你到JavaMail官网看一下API或下载Java Doc API文档。
求java实现邮件发送的源代码
需要用到javamail的jar包,网上有。
找不到把邮箱贴出来,我发给你。
package test.servlet;import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import .AddressException;
import Address;
import .MimeMessage;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;public class SendMailServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 2960000940515881314L;
private ServletConfig config = null;
private static final String CONTENT_TYPE = "text/html"; public void init(ServletConfig config1) throws ServletException {
this.config = config1;
} final public ServletConfig getServletConfig() {
return config;
} /**
* Constructor of the object.
*/
public SendMailServlet() {
super();
} /**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy();
} /**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error urred
* @throws IOException if an error urred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
} /**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error urred
* @throws IOException if an error urred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String to_mail=codeToString(request.getParameter("to"));
String to_title=codeToString(request.getParameter("title"));
String to_content=codeToString(request.getParameter("content"));
Properties props=new Properties();//也可用Properties props = System.getProperties(); //
props.put("mail.smtp.host","localhost");//存储发送邮件服务器的信息
props.put("mail.smtp.auth","true");//同时通过验证
Session s=Session.getInstance(props);//根据属性新建一个邮件会话
s.setDebug(true); //由邮件会话新建一个消息对象
MimeMessage message=new MimeMessage(s);//由邮件会话新建一个消息对象 //设置邮件
Address from;
try {
from = new Address("06254054@");
message.setFrom(from);//设置发件人
Address to=new Address(to_mail);
message.setRecipient(Message.RecipientType.TO,to);//设置收件人,并设置其接收类型为TO
message.setSubject(to_title);//设置主题
message.setText(to_content);//设置信件内容
message.setSentDate(new Date());//设置发信时间
//发送邮件
message.saveChanges();//存储邮件信息
Transport transport=s.getTransport("smtp");
//以smtp方式登录邮箱,第一个参数是发送邮件用的邮件服务器SMTP地址,第二个参数为用户名,第三个参数为密码
transport.connect("localhost",8479,"","");
transport.sendMessage(message,message.getAllRecipients());//发送邮件,其中第二个参数是所有已设好的收件人地址
transport.close();
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
out.print("ess");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} }
public String codeToString(String str) {//处理中文字符串的函数
String s=str;
try {
byte tempB[]=s.getBytes("ISO-8859-1");
s=new String(tempB);
return s;
} catch(Exception e) {
return s;
}
}
}
求JAVA发送邮件代码
import?java.io.IOException;
import?java.io.InputStream;
import?java.util.Properties;
import?javax.mail.Message;
import?javax.mail.MessagingException;
import?javax.mail.Session;
import?javax.mail.Transport;
import?Address;
import?.MimeMessage;
import?.MimeUtility;
public?class?JavaMail?{
????/**
?????*?Message对象将存储我们实际发送的电子邮件信息,
?????*?Message对象被作为一个MimeMessage对象来创建并且需要知道应当选择哪一个JavaMail?session。
?????*/
????private?MimeMessage?message;
????/**
?????*?Session类代表JavaMail中的一个邮件会话。
?????*?每一个基于JavaMail的应用程序至少有一个Session(可以有任意多的Session)。
?????*?
?????*?JavaMail需要Properties来创建一个session对象。
?????*?寻找"mail.smtp.host"????属性值就是发送邮件的主机
?????*?寻找"mail.smtp.auth"????身份验证,目前免费邮件服务器都需要这一项
?????*/
????private?Session?session;
????/***
?????*?邮件是既可以被发送也可以被受到。
JavaMail使用了两个不同的类来完成这两个功能:Transport?和?Store。
?
?????*?Transport?是用来发送信息的,而Store用来收信。
对于这的教程我们只需要用到Transport对象。
?????*/
????private?Transport?transport;
????private?String?mailHost="";
????private?String?sender_username="";
????private?String?sender_password="";
????private?Properties?properties?=?new?Properties();
????/*
?????*?初始化方法
?????*/
????public?JavaMail(boolean?debug)?{
????????InputStream?in?=?JavaMail.class.getResourceAsStream("MailServer.properties");
????????try?{
????????????properties.load(in);
????????????this.mailHost?=?properties.getProperty("mail.smtp.host");
????????????this.sender_username?=?properties.getProperty("mail.sender.username");
????????????this.sender_password?=?properties.getProperty("mail.sender.password");
????????}?catch?(IOException?e)?{
????????????e.printStackTrace();
????????}
????????session?=?Session.getInstance(properties);
????????session.setDebug(debug);//开启后有调试信息
????????message?=?new?MimeMessage(session);
????}
????/**
?????*?发送邮件
?????*?
?????*?@param?subject
?????*????????????邮件主题
?????*?@param?sendHtml
?????*????????????邮件内容
?????*?@param?receiveUser
?????*????????????收件人地址
?????*/
????public?void?doSendHtmlEmail(String?subject,?String?sendHtml,
????????????String?receiveUser)?{
????????try?{
????????????//?发件人
????????????//Address?from?=?new?Address(sender_username);
????????????//?下面这个是设置发送人的Nick?name
????????????Address?from?=?new?Address(MimeUtility.encodeWord("幻影")+"?<"+sender_username+">");
????????????message.setFrom(from);
????????????//?收件人
????????????Address?to?=?new?Address(receiveUser);
????????????message.setRecipient(Message.RecipientType.TO,?to);//还可以有CC、BCC
????????????//?邮件主题
????????????message.setSubject(subject);
????????????String?content?=?sendHtml.toString();
????????????//?邮件内容,也可以使纯文本"text/plain"
????????????message.setContent(content,?"text/html;charset=UTF-8");
????????????//?保存邮件
????????????message.saveChanges();
????????????transport?=?session.getTransport("smtp");
????????????//?smtp验证,就是你用来发邮件的邮箱用户名密码
????????????transport.connect(mailHost,?sender_username,?sender_password);
????????????//?发送
????????????transport.sendMessage(message,?message.getAllRecipients());
????????????//System.out.println("send?ess!");
????????}?catch?(Exception?e)?{
????????????e.printStackTrace();
????????}finally?{
????????????if(transport!=null){
????????????????try?{
????????????????????transport.close();
????????????????}?catch?(MessagingException?e)?{
????????????????????e.printStackTrace();
????????????????}
????????????}
????????}
????}
????public?static?void?main(String[]?args)?{
????????JavaMail?se?=?new?JavaMail(false);
????????se.doSendHtmlEmail("邮件主题",?"邮件内容",?"xxx@");
????}
}