java实现基于SMTP发送邮件的方法
本文实例讲述了java实现基于SMTP发送邮件的方法。分享给大家供大家参考。具体实现方法如下:
importjava.util.Date; importjava.util.Properties; importjavax.mail.Authenticator; importjavax.mail.Message; importjavax.mail.PasswordAuthentication; importjavax.mail.Session; importjavax.mail.Transport; importjavax.mail.internet.InternetAddress; importjavax.mail.internet.MimeMessage; importorg.apache.log4j.Logger; publicclassMailUtil{ privatestaticLoggerlogger=Logger.getLogger(MailUtil.class); /** *发送邮件 * *@paramsmtp *SMTP服务器 *@paramuser *用户名 *@parampassword *密码 *@paramsubject *标题 *@paramcontent *邮件内容 *@paramfrom *发件人邮箱 *@paramto *收件人邮箱 */ publicstaticvoidsend(Stringsmtp,finalStringuser, finalStringpassword,Stringsubject,Stringcontent,Stringfrom, Stringto){ try{ Propertiesprops=newProperties(); props.put("mail.smtp.host",smtp); props.put("mail.smtp.auth","true"); Sessionssn=Session.getInstance(props,newAuthenticator(){ @Override protectedPasswordAuthenticationgetPasswordAuthentication(){ returnnewPasswordAuthentication(user,password); } }); MimeMessagemessage=newMimeMessage(ssn); //由邮件会话新建一个消息对象 InternetAddressfromAddress=newInternetAddress(from); //发件人的邮件地址 message.setFrom(fromAddress); //设置发件人 InternetAddresstoAddress=newInternetAddress(to); //收件人的邮件地址 message.addRecipient(Message.RecipientType.TO,toAddress); //设置收件人 message.setSubject(subject); //设置标题 message.setText(content); //设置内容 message.setSentDate(newDate()); //设置发信时间 Transporttransport=ssn.getTransport("smtp"); transport.connect(smtp,user,password); transport.sendMessage(message,message .getRecipients(Message.RecipientType.TO)); //transport.send(message); transport.close(); logger.info("邮件发送成功"); }catch(Exceptione){ logger.warn("邮件发送失败",e); } } }
希望本文所述对大家的java程序设计有所帮助。