java发送邮件

public class SendEmail
{

    /**
     * 做该例子出现的异常
     * 1、Exception in thread "main" java.lang.NoClassDefFoundError: 
     * com/sun/mail/util/LineInputStream
     *(将javaee5换成jvaee6)
     * 2、Could not connect to SMTP host: localhost, port: 25
     *(是端口号设置不正确,用哪个邮箱发送邮件就要设置相应的smtp host,例如,163的是smtp.163.com)
     * 3、553 Local user only,163 smtp4,DtGowAAXE1vW5kBYngBsIQ--.47014S2 1480648406
     * (设置的发送邮箱和端口不对应)
     * 4、553 authentication is required,163 smtp4,DtGowACH2ywr50BYJRlsIQ--.16129S2 1480648491
     * (这里用163邮箱发送需要验证)
     * 设置property.put("mail.smtp.auth","true")注意,不是property.put("mail.smtp.auth",true)
     * 重写Authenticator类的getPasswordAuthentication方法设置用户名和密码
     * @param args
     */
    public static void main(String[] args)
    {
        final String from = "XXX@163.com";
        final String pass = "XXX";
        String to = "XXX@qq.com";
        String host = "smtp.163.com";
        
        Properties property = System.getProperties();
        
        property.setProperty("mail.smtp.host", host);
        property.put("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(property,new Authenticator(){
            public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(from,pass);
            }
        });
        
        MimeMessage message = new MimeMessage(session);
        
        try
        {
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            
            message.setSubject("this is subject");
            
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent("<a href=\"www.baidu.com\">点击此处</a>","text/html");
            
            Multipart mutipart = new MimeMultipart();
            mutipart.addBodyPart(messageBodyPart);
            
            /*附件部分*/
            messageBodyPart = new MimeBodyPart();
            String filename = "D:/Test/email.ser";
            DataSource dataSource = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(dataSource));
            messageBodyPart.setFileName(filename);
            mutipart.addBodyPart(messageBodyPart);
            message.setContent(mutipart);
            Transport.send(message);
            System.out.println("the email is send successful!");
        }
        catch( AddressException e )
        {
            e.printStackTrace();
        }
        catch( MessagingException e )
        {
            e.printStackTrace();
        }
    }

}

 

转载于:https://my.oschina.net/zerzer/blog/798737

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值