• Java发送邮件的简单实现


    使用Oracle官方的JavaMail进行实现,JavaMail下载地址:https://java.net/projects/javamail/pages/Home
    将下载好的jar包加入到工程路径中就OK了,我使用的是最新的1.5.2版本号的javax.mail.jar。

    关于邮件协议可參考:什么是POP3、SMTP和IMAP?
    以下的演示样例中是通过我的新浪邮箱(theonegis@sina.cn)给QQ邮箱(123456789@qq.com不知道是谁的邮箱)发邮件。以下给出实现代码:

    import java.util.Date;
    import java.util.Properties;
    
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.MimeMessage;
    
    public class SimpleMail {
        public static void main(String[] args) {
            Properties props = new Properties();
            //这里使用smtp协议发送邮件。我的新浪邮箱是.cn的不是.com的,所以smtpserver为smtp.sina.cn
            props.put("mail.smtp.host", "smtp.sina.cn");
            Session session = Session.getInstance(props, null);
    
            try {
                MimeMessage msg = new MimeMessage(session);
                //设置发件人邮箱
                msg.setFrom("theonegis@sina.cn");
                //设置收件人邮箱
                msg.setRecipients(Message.RecipientType.TO, "123456789@qq.com");
                //设置主题
                msg.setSubject("This is a test");
                //设置日期
                msg.setSentDate(new Date());
                //设置正文内容
                msg.setText("How are you?

    This is a test, please do not reply!"); //发送邮件,參数为邮件信息,发件人邮箱和发件人邮箱password Transport.send(msg, "theonegis@sina.cn", "这里是发件人的password"); } catch (MessagingException mex) { System.err.println("Send failed! Exception: " + mex); } } }

    JavaMail中比較重要的的类是Session、Store和Folder。

  • 相关阅读:
    Spring学习笔记
    Bash编程(6) String操作
    Bash编程(5) Shell方法
    Bash编程(4) 参数与变量
    Bash编程(2) 循环与分支
    CentOS 升级 openSSH
    Bash编程(1) 基础
    DNS配置
    资料收集:学习 Linux/*BSD/Unix 的 30 个最佳在线文档
    【数位DP】[LOJ10168] 恨7不成妻
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5271279.html
Copyright © 2020-2023  润新知