解决JavaMail无法发送邮件的错误(在J2EE项目中)

这学期的课程是一个j2ee项目,上次老师检查的时候说我们项目在注册的时候,要有一个邮箱验证的功能,不然谁都能去注册,这样会出现恶意注册。于是网上搜了一下大致知道可以用JavaMail给解决问题。不过试了一下,出现了以下异常:
1.Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/LineInputStream
2.Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/BEncoderStream

费解,以为自己代码写出问题了。到Oschina的代码共享区搜了一段代码,结果错误依然存在。网上大牛说java EE 5.0同JavaMail冲突,搜到一种解决办法:
将javaee.jar里面avax下有activation与mail两个文件夹删除
具体路径如下:(我们项目用的是 MyEclipse 8.5,其他版本应该也类似)
MyEclipse安装路径\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.5.0.me201003231033\data\libraryset\EE_5\javaee.jar

用winrar 打开javaee.jar,然后找到 activation与mail,将这两个文件夹删除,然后在你的项目里面导入mail.jar与activation.jar这两个包.于是乎,就可以在你的项目中利用JavaMail发送文件了。
发送邮件代码:来自于[url]http://www.oschina.net/code/snippet_12_1350[/url]

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
* 使用Gmail发送邮件
* @author Winter Lau
*/
public class GmailSender {

public static void main(String[] args) throws AddressException, MessagingException {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
// Get a Properties object
Properties props = System.getProperties();
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.auth", "true");
final String username = "[邮箱帐号]";
final String password = "[邮箱密码]";
Session session = Session.getDefaultInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}});

// -- Create a new message --
Message msg = new MimeMessage(session);

// -- Set the FROM and TO fields --
msg.setFrom(new InternetAddress(username + "@mo168.com"));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[收件人地址]",false));
msg.setSubject("Hello");
msg.setText("How are you");
msg.setSentDate(new Date());
Transport.send(msg);

System.out.println("Message sent.");
}
}



下面提供修改后的javaee.jar和需要导入到项目中去的包
另外就是一个示例。示例代码来自于[url]http://www.oschina.net/code/snippet_12_1350[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值