zoukankan      html  css  js  c++  java
  • 电子邮件发送具体过程

    我们在生活中经常收发电子邮件,这里先了解一下邮件的收发过程。至于代码方面,以后有时间会继续补充。。。。。待续

    一、发送邮件的过程(SMTP为例)

                              图-1  发送邮件的具体过程

    注意:这里的用户代理相当于用户电脑上的某一款软件,也可以是浏览器(利用web邮箱接收邮件)。

    二、javaMail编程

    1、代码

    /*
     * 项目内容:用qq邮箱给网易邮箱发送一条信息
     */
    public class JavaMailTest {
        public static void main(String[] args) throws Exception{
            //获取并设置系统参数
            Properties properties=System.getProperties();
            properties.setProperty("mail.smtp.auth", "true");
            properties.setProperty("mail.smtp.host", "smtp.qq.com");            //指定发送主机为qq邮件服务器
            //QQ邮箱需要设置SSL加密
            MailSSLSocketFactory mailSSLSocketFactory=new MailSSLSocketFactory();
            mailSSLSocketFactory.setTrustAllHosts(true);                        //信任所有主机
            properties.setProperty("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
            //创建一个邮件回话,并给出用户名和密码,供系统登录qq服务器
            Session session=Session.getDefaultInstance(properties,new Authenticator() {
                 public PasswordAuthentication getPasswordAuthentication(){
                    return new PasswordAuthentication("****@qq.com", "*****");  //用户名和密码(此处应该为授权码)
                }
            });
            //创建一个邮件,并设置邮件内容、邮件主题、收件人、发送人
            MimeMessage message=new MimeMessage(session);
            message.setFrom(new InternetAddress("********@qq.com"));    //发送人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress("******@163.com"));//收件人
            message.setSubject("给XX的一封信");
            message.setText("终于完事了");
            //发送
            Transport.send(message);
            System.out.println("完事了,老大");
        }
    }

     2、编程时遇到的异常

    异常:  javax.mail.AuthenticationFailedException: 530 Error: A secure connection is requiered(such as ssl). More information at http://service.mail.qq.com/cgi-bin/help?id=28

    这里异常是说:建立一个牢固的链接是必要的,需要提供SSL加密。(这里可能是为了qq服务器更加安全,腾讯公司设置的)。所以需要加上以下四行代码:

    MailSSLSocketFactory mailSSLSocketFactory=new MailSSLSocketFactory();
    mailSSLSocketFactory.setTrustAllHosts(true);                        //信任所有主机
    properties.setProperty("mail.smtp.ssl.enable", "true");
    properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);

    3、链接

    我这里只是为了练习一下javaMail,关于javaMail更加详细的用法,请参考:http://www.runoob.com/java/java-sending-email.html

  • 相关阅读:
    Hibernate映射
    hibernate 大对象类型的hibernate映射
    Hibernate映射文件详解(News***.hbm.xml)二
    Hibernate映射文件详解(News***.hbm.xml)一
    hibernate的速度问题--hibernate.jdbc.fetch_size和 hibernate.jdbc.batch_size
    EF使用EntityTypeConfiguration配置映射关系
    数据对象的映射关系
    SQL SERVER索引
    WCF(三)相关技术的学习
    WCF(二) endpoint
  • 原文地址:https://www.cnblogs.com/azhi/p/7699754.html
Copyright © 2011-2022 走看看