求java发邮件代码,要能用哦 求java发邮件代码,要能用哦谢过啦 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 网上好多例子呀。比如http://www.tutorialspoint.com/java/java_sending_email.htm 邮件系统很简单哦,只有下面两个类: MailBean 和 SendMailOnTime 需要jar组件: activation.jar mail.jar log4j.jar 代码如下: /* * Created on 2005-9-7 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates * * Update on 2008-8-14 */ package javaMail; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.log4j.Logger; /** * @author panshengti 类功能 : 处理意见反馈邮件发送 调用 jar:activation.jar 、 mail.jar */ public class MailBean { public static Logger log = null ; static { log = Logger.getLogger (MailBean. class ); } // smtpHost 发件人所用到的 smtp 服务器 String smtpHost = "smtp.163.com" ; // from 发件人邮箱 String from = "[email protected]" ; // to 收件人邮箱 String to = "[email protected]" ; // subject 邮件标题 String subject = "receive a mail from [email protected]" ; // theMessage 邮件内容 StringBuffer theMessage = new StringBuffer(); /** * 固定的给 [email protected] ,[email protected] 发送邮件 * create date:2008- 8- 15 * author:Administrator * * @param smtpHost * @param from * @param subject * @param messageText * @throws MessagingException */ public void sendMessage(String smtpHost, String from, String subject, String messageText) throws MessagingException { SmtpAuth sa = new SmtpAuth(); sa.getuserinfo( "d-ear" , "123abc" ); java.util.Properties props = new java.util.Properties(); props.put( "mail.smtp.auth" , "true" ); props.put( "mail.smtp.host" , smtpHost); System. out .println( "Constructing message- from=" + from + " to=" + to ); InternetAddress fromAddress = new InternetAddress(from); InternetAddress[] toAddresss = new InternetAddress[2]; toAddresss[0] = new InternetAddress( "[email protected]" ); toAddresss[1] = new InternetAddress( "[email protected]" ); int i = 0; while (i < toAddresss. length ) { Session mailSession = Session.getDefaultInstance (props, sa); MimeMessage testMessage = new MimeMessage(mailSession); testMessage.setFrom(fromAddress); testMessage.addRecipient(javax.mail.Message.RecipientType. TO , toAddresss[i]); testMessage.setSentDate( new java.util.Date()); testMessage.setSubject(subject); testMessage.setText(messageText); Transport.send (testMessage); System. out .println( "A mail have been sent!" ); i++; } } /* * 由 163 服务器向目的邮箱发送邮件 * 邮件发送处理 @param stmHost,from,to,subject,messageText */ public void sendMessage(String smtpHost, String from, String to, String subject, String messageText) throws MessagingException { SmtpAuth sa = new SmtpAuth(); sa.getuserinfo( "d-ear" , "123abc" ); java.util.Properties props = new java.util.Properties(); props.put( "mail.smtp.auth" , "true" ); props.put( "mail.smtp.host" , smtpHost); System. out .println( "Constructing message- from=" + from + " to=" + to); InternetAddress fromAddress = new InternetAddress(from); InternetAddress toAddresss = new InternetAddress(to); Session mailSession = Session.getDefaultInstance (props, sa); MimeMessage testMessage = new MimeMessage(mailSession); testMessage.setFrom(fromAddress); testMessage.addRecipient(javax.mail.Message.RecipientType. TO , toAddresss); testMessage.setSentDate( new java.util.Date()); testMessage.setSubject(subject); testMessage.setText(messageText); Transport.send (testMessage); System. out .println( "A mail have been sent to " + to); } /** * 功能:群发功能 , 把所有的目的邮箱作为一个数组参数传入 * create date:2008- 8- 15 * author:Administrator * * @param smtpHost * @param from * @param to 目的邮箱数组 * @param subject * @param messageText * @throws MessagingException */ public void sendMessage(String smtpHost, String from, String[] to, String subject, String messageText) throws MessagingException { SmtpAuth sa = new SmtpAuth(); sa.getuserinfo( "d-ear" , "123abc" ); java.util.Properties props = new java.util.Properties(); props.put( "mail.smtp.auth" , "true" ); props.put( "mail.smtp.host" , smtpHost); System. out .println( "Constructing message- from=" + from + " to=" + to); InternetAddress fromAddress = new InternetAddress(from); InternetAddress[] toAddresss = new InternetAddress[to. length ]; for ( int len=0;len<to. length ;len++){ toAddresss[0] = new InternetAddress(to[len]); } int i = 0; while (i < toAddresss. length ) { Session mailSession = Session.getDefaultInstance (props, sa); MimeMessage testMessage = new MimeMessage(mailSession); testMessage.setFrom(fromAddress); testMessage.addRecipient(javax.mail.Message.RecipientType. TO , toAddresss[i]); testMessage.setSentDate( new java.util.Date()); testMessage.setSubject(subject); testMessage.setText(messageText); Transport.send (testMessage); System. out .println( "A mail have been sent to " +to[i]); i++; } } /* * 邮件用户名和密码认证 */ static class SmtpAuth extends javax.mail.Authenticator { private String user , password ; public void getuserinfo(String getuser, String getpassword) { user = getuser; password = getpassword; } protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication( user , password ); } } } package javaMail; import javax.mail.MessagingException; import org.apache.log4j.Logger; public class SendMailOnTime { public static Logger log = null ; static { log = Logger.getLogger (SendMailOnTime. class ); } /** * @param args */ public static void sendMail(String str) { MailBean mail = new MailBean(); try { mail.sendMessage( "smtp.163.com" , "[email protected]" , "rent information" , str); } catch (MessagingException e) { System. out .println( "mail send error !" ); log .debug( "mail send error !" + e.getMessage()); e.printStackTrace(); } System. out .println( "Mail have been sended ." ); } /** * 给一个指定邮箱发送指定的邮件内容 create date:2008- 8- 15 author:Administrator * * @param str */ public static void sendMail(String toMail, String content) { MailBean mail = new MailBean(); try { mail.sendMessage( "smtp.163.com" , "[email protected]" , toMail, "spider information" , content); } catch (MessagingException e) { System. out .println( "mail send error !" ); log .debug( "mail send error !" + e.getMessage()); e.printStackTrace(); } System. out .println( "Mail have been sended ." ); } /** * 指定目的邮箱数组进行群发 create date:2008- 8- 15 author:Administrator * * @param toMail * @param content */ public static void sendMail(String[] toMail, String content) { MailBean mail = new MailBean(); try { mail.sendMessage( "smtp.163.com" , "[email protected]" , toMail, "spider information" , content); } catch (MessagingException e) { System. out .println( "mail send error !" ); log .debug( "mail send error !" + e.getMessage()); e.printStackTrace(); } System. out .println( "Mail have been sended ." ); } } 还有一个 注释的 学习有帮助import javax.mail.Transport;import javax.mail.internet.InternetAddress;import java.util.Date;import javax.mail.Message.RecipientType;import javax.mail.internet.MimeMessage;import javax.mail.Message;import javax.mail.Session;import java.util.Properties;import javax.mail.MessagingException;import javax.mail.internet.MimeBodyPart;import javax.mail.Multipart;import javax.mail.internet.MimeMultipart;import org.apache.log4j.Logger;/** *//** *//** *//** * 发送Email类 */public class SendEmail { Logger logger=Logger.getLogger(this.getClass()); /** *//** *//** *//** * Email发送方法 * @param toemails 需要一个字符串参数,用来设置收件人地址,如果收件人为多个,则用","隔开 * @param content 邮件内容 * @param subject 邮件主题 * @return 邮件成功发送则返回true,否则返回false */ public boolean sendSimpleEmail(String toemails,String content,String subject){ boolean result=false; logger.info("进入发送Email类"); try { //创建属性对象 Properties props = new Properties(); //设置邮件传输协议为:smtp props.put("mail.transpost.protocol","smtp"); //设置邮件服务器地址 props.put("mail.smtp.host", "smtp.163.com"); //设置邮件验证为真 props.put("mail.smtp.auth", "true"); //设置邮件服务器端口 props.put("mail.smtp.port","25"); //调用验证类进行验证,需要参数发件人用户名和密码 logger.info("验证类实例化=============="); CheckSendEmail auth=new CheckSendEmail("lip009","lip009"); logger.info("验证通过"); //创建session对象 Session sendMailSession; sendMailSession = Session.getInstance(props, auth); //设置输出调试信息 sendMailSession.setDebug(true); logger.info("开始创建消息对象"); //创建信息对象 Message newMessage = new MimeMessage(sendMailSession); //输入发送信息 //设置发信人地址 logger.info("设置发信人地址"); newMessage.setFrom(new InternetAddress("[email protected]")); //设置收信人地址,只支持单用户发送// newMessage.setRecipient(Message.RecipientType.TO,new InternetAddress([email protected])); //设置收信人地址,可以支持多用户发送 logger.info("设置收信人地址"); newMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toemails)); //附件//============================================================================== //msgText是信件的正文,共有两行// String msgText = content; //msgAttachment是一段字符串作为附件内容// String msgAttachment = "This is an attachment string!";// MimeBodyPart mbp1 = new MimeBodyPart();// mbp1.setText(msgText); //把前面定义的msgText中的文字设定为邮件正文的内容 //创建附件部分// MimeBodyPart mbp2 = new MimeBodyPart(); //使用setText(text, charset)来加入附件// mbp2.setText(msgAttachment, "gb2312"); //创建Multipart// Multipart mp = new MimeMultipart();// mp.addBodyPart(mbp1);// mp.addBodyPart(mbp2); // 添加 Multipart到Message中// newMessage.setContent(mp);//============================================================================== //设置信件文本格式(当设置了附件,这里就不能有) logger.info("设置格式"); newMessage.setContent("SendMail", "text/html"); //设置信件主题 logger.info("设置主题"); newMessage.setSubject(subject); //设置信件发送日期 logger.info("设置发送日期"); newMessage.setSentDate(new Date()); //设置信件正文(当设置了附件,这里就不能有) newMessage.setText(content); logger.info("设置完消息"); //创建对象 Transport transport; transport = sendMailSession.getTransport("smtp"); logger.info("将要发送"); //发送 result=true; transport.send(newMessage);//此处总是抛出异常,让人很是郁闷,但是邮件却发送成功! logger.info("恭喜你!您的邮件已经成功发送!"); } catch (MessagingException ex) {// ex.printStackTrace(); } return result; }} http://blog.csdn.net/peihexian/archive/2006/12/25/1460473.aspx import java.util.Properties; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.URLName; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; public class SendMail { public SendMail() { } public static void main(String[] args) { // 初始化信息 String sender = "[email protected]"; //发件人 String password = "xxxxxx"; String smtpServer = "smtp.163.com"; String recipient = "[email protected]"; //收件人 String subject = "测试邮件主题"; String content = "测试邮件内容"; String fileAttachment = ""; //附件 // 配置服务器属性 Properties proper = new Properties(); proper.put("mail.smtp.host", smtpServer); // smtp服务器 proper.put("mail.smtp.auth", "true"); // 是否smtp认证 proper.put("mail.smtp.port", "25"); // 设置smtp端口 proper.put("mail.transport.protocol", "smtp"); // 发邮件协议 proper.put("mail.store.protocol", "pop3"); // 收邮件协议 // 配置邮件接收地址 InternetAddress[] receiveAddress = new InternetAddress[1]; try { receiveAddress[0] = new InternetAddress(recipient); } catch (AddressException e) { e.printStackTrace(); } // smtp认证,获取Session SmtpAuth sa = new SmtpAuth(); sa.setUserinfo(sender, password); Session session = Session.getInstance(proper, sa); session.setPasswordAuthentication(new URLName(smtpServer), sa.getPasswordAuthentication()); // 构建邮件体 MimeMessage sendMess = new MimeMessage(session); MimeBodyPart mbp = new MimeBodyPart(); MimeMultipart mmp = new MimeMultipart(); try { // 邮件文本内容 mbp.setContent(content, "text/plain; charset=GBK"); mmp.addBodyPart(mbp); // 附件处理 if(fileAttachment!=null&&fileAttachment!=""){ DataSource source = new FileDataSource(fileAttachment); String name = source.getName(); mbp = new MimeBodyPart(); mbp.setDataHandler(new DataHandler(source)); mbp.setFileName(name); mmp.addBodyPart(mbp); } // 邮件整体 sendMess.setSubject(subject); sendMess.setContent(mmp); // 发送邮件 sendMess.setFrom(new InternetAddress(sender)); sendMess.setRecipients(Message.RecipientType.TO, receiveAddress); Transport.send(sendMess); System.out.println("发送成功"); } catch (MessagingException ex) { ex.printStackTrace(); } } } javax.mail.AuthenticationFailedException: failed to connect at javax.mail.Service.connect(Service.java:322) at javax.mail.Service.connect(Service.java:172) at javax.mail.Service.connect(Service.java:121) at javax.mail.Transport.send0(Transport.java:190) at javax.mail.Transport.send(Transport.java:120) at mail7.SendMail.main(SendMail.java:79)用户名和密码都对 你的邮箱是否打开了POP/SMTP!!! 有用 spring 里面的mail包做的例子,在内网里面可以发。外网没有试过。 DiskFileUpload上传文件的问题 ibatis初学(急) 文件上传的问题 有关 axis WebService 发布的问题 hibernate映射文件,用list集合排序问题 关于类型转换的疑问。 jboss4.0.5 如何加载本地硬盘中的jar包 httpclient3.1困惑 哪里下载cloudscape数据库? EJB现在还有用的吗?他的发展前景如何? j2ee如何和c建立socket连接 struts节点相关问题
邮件系统很简单哦,只有下面两个类:
MailBean 和 SendMailOnTime
需要jar组件:
activation.jar
mail.jar
log4j.jar 代码如下: /* * Created on 2005-9-7 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates * * Update on 2008-8-14 */ package javaMail; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import org.apache.log4j.Logger; /** * @author panshengti 类功能 : 处理意见反馈邮件发送 调用 jar:activation.jar 、 mail.jar */ public class MailBean { public static Logger log = null ; static { log = Logger.getLogger (MailBean. class ); } // smtpHost 发件人所用到的 smtp 服务器 String smtpHost = "smtp.163.com" ; // from 发件人邮箱 String from = "[email protected]" ; // to 收件人邮箱 String to = "[email protected]" ; // subject 邮件标题 String subject = "receive a mail from [email protected]" ; // theMessage 邮件内容 StringBuffer theMessage = new StringBuffer(); /** * 固定的给 [email protected] ,[email protected] 发送邮件 * create date:2008- 8- 15 * author:Administrator * * @param smtpHost * @param from * @param subject * @param messageText * @throws MessagingException */ public void sendMessage(String smtpHost, String from, String subject, String messageText) throws MessagingException { SmtpAuth sa = new SmtpAuth(); sa.getuserinfo( "d-ear" , "123abc" ); java.util.Properties props = new java.util.Properties(); props.put( "mail.smtp.auth" , "true" ); props.put( "mail.smtp.host" , smtpHost); System. out .println( "Constructing message- from=" + from + " to=" + to ); InternetAddress fromAddress = new InternetAddress(from); InternetAddress[] toAddresss = new InternetAddress[2]; toAddresss[0] = new InternetAddress( "[email protected]" ); toAddresss[1] = new InternetAddress( "[email protected]" ); int i = 0; while (i < toAddresss. length ) { Session mailSession = Session.getDefaultInstance (props, sa); MimeMessage testMessage = new MimeMessage(mailSession); testMessage.setFrom(fromAddress); testMessage.addRecipient(javax.mail.Message.RecipientType. TO , toAddresss[i]); testMessage.setSentDate( new java.util.Date()); testMessage.setSubject(subject); testMessage.setText(messageText); Transport.send (testMessage); System. out .println( "A mail have been sent!" ); i++; } } /* * 由 163 服务器向目的邮箱发送邮件 * 邮件发送处理 @param stmHost,from,to,subject,messageText */ public void sendMessage(String smtpHost, String from, String to, String subject, String messageText) throws MessagingException { SmtpAuth sa = new SmtpAuth(); sa.getuserinfo( "d-ear" , "123abc" ); java.util.Properties props = new java.util.Properties(); props.put( "mail.smtp.auth" , "true" ); props.put( "mail.smtp.host" , smtpHost); System. out .println( "Constructing message- from=" + from + " to=" + to); InternetAddress fromAddress = new InternetAddress(from); InternetAddress toAddresss = new InternetAddress(to); Session mailSession = Session.getDefaultInstance (props, sa); MimeMessage testMessage = new MimeMessage(mailSession); testMessage.setFrom(fromAddress); testMessage.addRecipient(javax.mail.Message.RecipientType. TO , toAddresss); testMessage.setSentDate( new java.util.Date()); testMessage.setSubject(subject); testMessage.setText(messageText); Transport.send (testMessage); System. out .println( "A mail have been sent to " + to); } /** * 功能:群发功能 , 把所有的目的邮箱作为一个数组参数传入 * create date:2008- 8- 15 * author:Administrator * * @param smtpHost * @param from * @param to 目的邮箱数组 * @param subject * @param messageText * @throws MessagingException */ public void sendMessage(String smtpHost, String from, String[] to, String subject, String messageText) throws MessagingException { SmtpAuth sa = new SmtpAuth(); sa.getuserinfo( "d-ear" , "123abc" ); java.util.Properties props = new java.util.Properties(); props.put( "mail.smtp.auth" , "true" ); props.put( "mail.smtp.host" , smtpHost); System. out .println( "Constructing message- from=" + from + " to=" + to); InternetAddress fromAddress = new InternetAddress(from); InternetAddress[] toAddresss = new InternetAddress[to. length ]; for ( int len=0;len<to. length ;len++){ toAddresss[0] = new InternetAddress(to[len]); } int i = 0; while (i < toAddresss. length ) { Session mailSession = Session.getDefaultInstance (props, sa); MimeMessage testMessage = new MimeMessage(mailSession); testMessage.setFrom(fromAddress); testMessage.addRecipient(javax.mail.Message.RecipientType. TO , toAddresss[i]); testMessage.setSentDate( new java.util.Date()); testMessage.setSubject(subject); testMessage.setText(messageText); Transport.send (testMessage); System. out .println( "A mail have been sent to " +to[i]); i++; } } /* * 邮件用户名和密码认证 */ static class SmtpAuth extends javax.mail.Authenticator { private String user , password ; public void getuserinfo(String getuser, String getpassword) { user = getuser; password = getpassword; } protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication( user , password ); } } } package javaMail; import javax.mail.MessagingException; import org.apache.log4j.Logger; public class SendMailOnTime { public static Logger log = null ; static { log = Logger.getLogger (SendMailOnTime. class ); } /** * @param args */ public static void sendMail(String str) { MailBean mail = new MailBean(); try { mail.sendMessage( "smtp.163.com" , "[email protected]" , "rent information" , str); } catch (MessagingException e) { System. out .println( "mail send error !" ); log .debug( "mail send error !" + e.getMessage()); e.printStackTrace(); } System. out .println( "Mail have been sended ." ); } /** * 给一个指定邮箱发送指定的邮件内容 create date:2008- 8- 15 author:Administrator * * @param str */ public static void sendMail(String toMail, String content) { MailBean mail = new MailBean(); try { mail.sendMessage( "smtp.163.com" , "[email protected]" , toMail, "spider information" , content); } catch (MessagingException e) { System. out .println( "mail send error !" ); log .debug( "mail send error !" + e.getMessage()); e.printStackTrace(); } System. out .println( "Mail have been sended ." ); } /** * 指定目的邮箱数组进行群发 create date:2008- 8- 15 author:Administrator * * @param toMail * @param content */ public static void sendMail(String[] toMail, String content) { MailBean mail = new MailBean(); try { mail.sendMessage( "smtp.163.com" , "[email protected]" , toMail, "spider information" , content); } catch (MessagingException e) { System. out .println( "mail send error !" ); log .debug( "mail send error !" + e.getMessage()); e.printStackTrace(); } System. out .println( "Mail have been sended ." ); } }
import javax.mail.internet.InternetAddress;
import java.util.Date;
import javax.mail.Message.RecipientType;
import javax.mail.internet.MimeMessage;
import javax.mail.Message;
import javax.mail.Session;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import org.apache.log4j.Logger;
/** *//** *//** *//**
* 发送Email类
*/public class SendEmail {
Logger logger=Logger.getLogger(this.getClass());
/** *//** *//** *//**
* Email发送方法
* @param toemails 需要一个字符串参数,用来设置收件人地址,如果收件人为多个,则用","隔开
* @param content 邮件内容
* @param subject 邮件主题
* @return 邮件成功发送则返回true,否则返回false
*/
public boolean sendSimpleEmail(String toemails,String content,String subject){
boolean result=false;
logger.info("进入发送Email类");
try {
//创建属性对象
Properties props = new Properties();
//设置邮件传输协议为:smtp
props.put("mail.transpost.protocol","smtp");
//设置邮件服务器地址
props.put("mail.smtp.host", "smtp.163.com");
//设置邮件验证为真
props.put("mail.smtp.auth", "true");
//设置邮件服务器端口
props.put("mail.smtp.port","25"); //调用验证类进行验证,需要参数发件人用户名和密码
logger.info("验证类实例化==============");
CheckSendEmail auth=new CheckSendEmail("lip009","lip009"); logger.info("验证通过");
//创建session对象
Session sendMailSession;
sendMailSession = Session.getInstance(props, auth);
//设置输出调试信息
sendMailSession.setDebug(true); logger.info("开始创建消息对象");
//创建信息对象
Message newMessage = new MimeMessage(sendMailSession); //输入发送信息
//设置发信人地址
logger.info("设置发信人地址");
newMessage.setFrom(new InternetAddress("[email protected]")); //设置收信人地址,只支持单用户发送
// newMessage.setRecipient(Message.RecipientType.TO,new InternetAddress([email protected])); //设置收信人地址,可以支持多用户发送
logger.info("设置收信人地址");
newMessage.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toemails));
//附件
//==============================================================================
//msgText是信件的正文,共有两行
// String msgText = content; //msgAttachment是一段字符串作为附件内容
// String msgAttachment = "This is an attachment string!";// MimeBodyPart mbp1 = new MimeBodyPart();// mbp1.setText(msgText); //把前面定义的msgText中的文字设定为邮件正文的内容 //创建附件部分
// MimeBodyPart mbp2 = new MimeBodyPart(); //使用setText(text, charset)来加入附件
// mbp2.setText(msgAttachment, "gb2312"); //创建Multipart
// Multipart mp = new MimeMultipart();// mp.addBodyPart(mbp1);
// mp.addBodyPart(mbp2); // 添加 Multipart到Message中
// newMessage.setContent(mp);
//==============================================================================
//设置信件文本格式(当设置了附件,这里就不能有)
logger.info("设置格式");
newMessage.setContent("SendMail", "text/html"); //设置信件主题
logger.info("设置主题");
newMessage.setSubject(subject); //设置信件发送日期
logger.info("设置发送日期");
newMessage.setSentDate(new Date()); //设置信件正文(当设置了附件,这里就不能有)
newMessage.setText(content);
logger.info("设置完消息");
//创建对象
Transport transport;
transport = sendMailSession.getTransport("smtp");
logger.info("将要发送"); //发送
result=true;
transport.send(newMessage);//此处总是抛出异常,让人很是郁闷,但是邮件却发送成功!
logger.info("恭喜你!您的邮件已经成功发送!");
}
catch (MessagingException ex) {
// ex.printStackTrace();
}
return result;
}
}
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class SendMail {
public SendMail() {
}
public static void main(String[] args) {
// 初始化信息
String sender = "[email protected]"; //发件人
String password = "xxxxxx";
String smtpServer = "smtp.163.com";
String recipient = "[email protected]"; //收件人
String subject = "测试邮件主题";
String content = "测试邮件内容";
String fileAttachment = ""; //附件
// 配置服务器属性
Properties proper = new Properties();
proper.put("mail.smtp.host", smtpServer); // smtp服务器
proper.put("mail.smtp.auth", "true"); // 是否smtp认证
proper.put("mail.smtp.port", "25"); // 设置smtp端口
proper.put("mail.transport.protocol", "smtp"); // 发邮件协议
proper.put("mail.store.protocol", "pop3"); // 收邮件协议
// 配置邮件接收地址
InternetAddress[] receiveAddress = new InternetAddress[1];
try {
receiveAddress[0] = new InternetAddress(recipient);
} catch (AddressException e) {
e.printStackTrace();
}
// smtp认证,获取Session
SmtpAuth sa = new SmtpAuth();
sa.setUserinfo(sender, password);
Session session = Session.getInstance(proper, sa);
session.setPasswordAuthentication(new URLName(smtpServer), sa.getPasswordAuthentication());
// 构建邮件体
MimeMessage sendMess = new MimeMessage(session);
MimeBodyPart mbp = new MimeBodyPart();
MimeMultipart mmp = new MimeMultipart();
try {
// 邮件文本内容
mbp.setContent(content, "text/plain; charset=GBK");
mmp.addBodyPart(mbp);
// 附件处理
if(fileAttachment!=null&&fileAttachment!=""){
DataSource source = new FileDataSource(fileAttachment);
String name = source.getName();
mbp = new MimeBodyPart();
mbp.setDataHandler(new DataHandler(source));
mbp.setFileName(name);
mmp.addBodyPart(mbp);
}
// 邮件整体
sendMess.setSubject(subject);
sendMess.setContent(mmp);
// 发送邮件
sendMess.setFrom(new InternetAddress(sender));
sendMess.setRecipients(Message.RecipientType.TO, receiveAddress);
Transport.send(sendMess);
System.out.println("发送成功");
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
} javax.mail.AuthenticationFailedException: failed to connect
at javax.mail.Service.connect(Service.java:322)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at mail7.SendMail.main(SendMail.java:79)
用户名和密码都对