使用JMail发送邮件

使用JMail做最简单的文本邮件发送:

第一步、下载JMail和JAF

第二步、解压放到本地classpath中

第三步、使用:

public class MailService{
    private static final String host="smtp.ym.163.com";--------------定义邮件服务器smtp地址
    private static final String user="admin@163.com";----------------定义登陆邮箱账号
    private static final String pwd="*********";---------------------定义登陆邮箱密码
    private String subject="";-----------------------------------------定义发送标题字符串
    
    public void Send(String to,String content){-----------------------定义发送到的参数以及发送的内容
        subject="邮件标题";
        Properties props=System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        try{
            Session session=Session.getDefaultInstance(props);
            MimeMessage msg=new MimeMessage(session);
            msg.setFrom(new InternetAddress(user));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            msg.setSubject(subject);
            msg.setText(content);
            msg.saveChanges();
            Transport trans=session.getTransport("smtp");
            trans.connect(host, user, pwd);
            trans.sendMessage(msg, msg.getAllRecipients());
            trans.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        
    }
    public boolean SendMail(String content) throws Exception{
        Send("who@163.com",content);
        return true;
    }

}

备注:上面的方法都是从网上找资料写出来的,具体意义参考其他专业人士写的,我这个仅供参考,另外,如果要发送带换行的文本,在字符串content中使用" "来换行!

原文地址:https://www.cnblogs.com/ichemmwangd/p/4679736.html