zoukankan      html  css  js  c++  java
  • 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。

  • 相关阅读:
    RabbitMQ消费端自定义监听器DefaultConsumer
    RabbitMQ exchange交换机类型
    RabbitMQ 快速入门
    chrome jsonView插件安装
    谈谈令人头大的prototype 和__proto__
    原生JS写一个淡入淡出轮播图
    模拟聊天对话框
    全选反选的小案例
    原生js做一个简单的进度条
    点击回到顶部的按钮
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5271279.html
Copyright © 2011-2022 走看看