java发送邮件的实现过程,java收发邮件

发布时间:2022-11-19

本文目录一览:

  1. 怎么用JAVA实现邮件发送
  2. 怎样用java发送邮件
  3. java 怎么实现发送邮件例子
  4. 如何使用Java发送qq邮件
  5. Java收发邮件过程中具体的功能是怎么实现的

怎么用JAVA实现邮件发送

一个小例子,也可使用其他api

import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class Test {
    // test
    public static void main(String[] args) throws Exception {
        sendEmail("smtp.163.com", "测试", "测试", "!!!收件人地址!!!", "!!!发件人邮箱用户名!!!", "!!!邮箱密码!!!", "发件人昵称");
    }
    /**
     *
     * @param smtp
     * @throws Exception
     */
    public static void sendEmail(String emailServer, String subject, String mailBody, String receiver, final String username, final String password, String nickname) throws Exception {
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", emailServer);
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        session.setDebug(true);
        MimeMessage mimeMsg = new MimeMessage(session);
        Multipart mp = new MimeMultipart();
        mimeMsg.setSubject(MimeUtility.encodeText(subject, "utf-8", null));
        nickname = MimeUtility.encodeText(nickname, "utf-8", null);
        mimeMsg.setFrom(new InternetAddress(username, nickname, "UTF-8"));
        BodyPart bp = new MimeBodyPart();
        bp.setContent(mailBody, "text/html;charset=utf-8");
        mp.addBodyPart(bp);
        mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
        mimeMsg.setContent(mp);
        mimeMsg.saveChanges();
        Transport transport = session.getTransport();
        transport.connect(username, password);
        Address[] allRecipients = mimeMsg.getAllRecipients();
        transport.sendMessage(mimeMsg, allRecipients);
        transport.close();
    }
}

怎样用java发送邮件

首先下载 JavaMail jar 包,并导入到项目中。下载地址 编写代码,代码如下:

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class App45 {
    public static void main(String[] args) throws AddressException, MessagingException {
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", "邮件发送服务器");
        properties.setProperty("mail.smtp.auth", "true");
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 设置发件人邮件帐号和密码
                return new PasswordAuthentication("邮件帐号", "密码");
            }
        });
        MimeMessage message = new MimeMessage(session);
        // 设置发件人邮件地址
        message.setFrom(new InternetAddress("发件人邮件地址"));
        // 设置收件人邮件地址
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("收件人邮件地址"));
        message.setSubject("这里是邮件主题。");
        message.setText("这里是邮件内容。");
        Transport.send(message);
    }
}

java 怎么实现发送邮件例子

第一个类:MailSenderInfo.java

package com.util.mail;
/**
 * 发送邮件需要使用的基本信息
 * author by wangfun
 * 小说520
 */
import java.util.Properties;
public class MailSenderInfo {
    // 发送邮件的服务器的IP和端口
    private String mailServerHost;
    private String mailServerPort = "25";
    // 邮件发送者的地址
    private String fromAddress;
    // 邮件接收者的地址
    private String toAddress;
    // 登陆邮件发送服务器的用户名和密码
    private String userName;
    private String password;
    // 是否需要身份验证
    private boolean validate = false;
    // 邮件主题
    private String subject;
    // 邮件的文本内容
    private String content;
    // 邮件附件的文件名
    private String[] attachFileNames;
    /**
     * 获得邮件会话属性
     */
    public Properties getProperties() {
        Properties p = new Properties();
        p.put("mail.smtp.host", this.mailServerHost);
        p.put("mail.smtp.port", this.mailServerPort);
        p.put("mail.smtp.auth", validate ? "true" : "false");
        return p;
    }
    public String getMailServerHost() {
        return mailServerHost;
    }
    public void setMailServerHost(String mailServerHost) {
        this.mailServerHost = mailServerHost;
    }
    public String getMailServerPort() {
        return mailServerPort;
    }
    public void setMailServerPort(String mailServerPort) {
        this.mailServerPort = mailServerPort;
    }
    public boolean isValidate() {
        return validate;
    }
    public void setValidate(boolean validate) {
        this.validate = validate;
    }
    public String[] getAttachFileNames() {
        return attachFileNames;
    }
    public void setAttachFileNames(String[] fileNames) {
        this.attachFileNames = fileNames;
    }
    public String getFromAddress() {
        return fromAddress;
    }
    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getToAddress() {
        return toAddress;
    }
    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getSubject() {
        return subject;
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String textContent) {
        this.content = textContent;
    }
}

第二个类:SimpleMailSender.java

package com.util.mail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
 * 简单邮件(不带附件的邮件)发送器
 * BT下载
 */
public class SimpleMailSender {
    /**
     * 以文本格式发送邮件
     * @param mailInfo 待发送的邮件的信息
     */
    public boolean sendTextMail(MailSenderInfo mailInfo) {
        // 判断是否需要身份认证
        MyAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        if (mailInfo.isValidate()) {
            // 如果需要身份认证,则创建一个密码验证器
            authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            // 根据session创建一个邮件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from = new InternetAddress(mailInfo.getFromAddress());
            // 设置邮件消息的发送者
            mailMessage.setFrom(from);
            // 创建邮件的接收者地址,并设置到邮件消息中
            Address to = new InternetAddress(mailInfo.getToAddress());
            mailMessage.setRecipient(Message.RecipientType.TO, to);
            // 设置邮件消息的主题
            mailMessage.setSubject(mailInfo.getSubject());
            // 设置邮件消息发送的时间
            mailMessage.setSentDate(new Date());
            // 设置邮件消息的主要内容
            String mailContent = mailInfo.getContent();
            mailMessage.setText(mailContent);
            // 发送邮件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }
    /**
     * 以HTML格式发送邮件
     * @param mailInfo 待发送的邮件信息
     */
    public static boolean sendHtmlMail(MailSenderInfo mailInfo){
        // 判断是否需要身份认证
        MyAuthenticator authenticator = null;
        Properties pro = mailInfo.getProperties();
        //如果需要身份认证,则创建一个密码验证器
        if (mailInfo.isValidate()) {
            authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
        }
        // 根据邮件会话属性和密码验证器构造一个发送邮件的session
        Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
        try {
            // 根据session创建一个邮件消息
            Message mailMessage = new MimeMessage(sendMailSession);
            // 创建邮件发送者地址
            Address from = new InternetAddress(mailInfo.getFromAddress());
            // 设置邮件消息的发送者
            mailMessage.setFrom(from);
            // 创建邮件的接收者地址,并设置到邮件消息中
            Address to = new InternetAddress(mailInfo.getToAddress());
            // Message.RecipientType.TO属性表示接收者的类型为TO
            mailMessage.setRecipient(Message.RecipientType.TO, to);
            // 设置邮件消息的主题
            mailMessage.setSubject(mailInfo.getSubject());
            // 设置邮件消息发送的时间
            mailMessage.setSentDate(new Date());
            // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
            Multipart mainPart = new MimeMultipart();
            // 创建一个包含HTML内容的MimeBodyPart
            BodyPart html = new MimeBodyPart();
            // 设置HTML内容
            html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
            mainPart.addBodyPart(html);
            // 将MiniMultipart对象设置为邮件内容
            mailMessage.setContent(mainPart);
            // 发送邮件
            Transport.send(mailMessage);
            return true;
        } catch (MessagingException ex) {
            ex.printStackTrace();
        }
        return false;
    }
}

第三个类:MyAuthenticator.java

package com.util.mail;
import javax.mail.*;
public class MyAuthenticator extends Authenticator {
    String userName = null;
    String password = null;
    public MyAuthenticator(){}
    public MyAuthenticator(String username, String password) {
        this.userName = username;
        this.password = password;
    }
    protected PasswordAuthentication getPasswordAuthentication(){
        return new PasswordAuthentication(userName, password);
    }
}

下面给出使用上面三个类的代码:

public static void main(String[] args){
    //这个类主要是设置邮件
    MailSenderInfo mailInfo = new MailSenderInfo();
    mailInfo.setMailServerHost("smtp.163.com");
    mailInfo.setMailServerPort("25");
    mailInfo.setValidate(true);
    mailInfo.setUserName("han2000lei@163.com");
    mailInfo.setPassword("**********");//您的邮箱密码
    mailInfo.setFromAddress("han2000lei@163.com");
    mailInfo.setToAddress("han2000lei@163.com");
    mailInfo.setSubject("设置邮箱标题 如 中国桂花网");
    mailInfo.setContent("设置邮箱内容 如 中国桂花网 是中国最大桂花网站==");
    //这个类主要来发送邮件
    SimpleMailSender sms = new SimpleMailSender();
    sms.sendTextMail(mailInfo);//发送文体格式
    sms.sendHtmlMail(mailInfo);//发送html格式
}

最后,给出朋友们几个注意的地方:

  1. 使用此代码你可以完成你的javamail的邮件发送功能。三个类缺一不可。
  2. 这三个类我打包是用的com.util.mail包,如果不喜欢,你可以自己改,但三个类文件必须在同一个包中
  3. 不要使用你刚刚注册过的邮箱在程序中发邮件,如果你的163邮箱是刚注册不久,那你就不要使用“smtp.163.com”。因为你发不出去。刚注册的邮箱是不会给你这种权限的,也就是你不能通过验证。要使用你经常用的邮箱,而且时间比较长的。
  4. 另一个问题就是mailInfo.setMailServerHost("smtp.163.com");与mailInfo.setFromAddress("han2000lei@163.com");这两句话。即如果你使用163smtp服务器,那么发送邮件地址就必须用163的邮箱,如果不的话,是不会发送成功的。
  5. 关于javamail验证错误的问题,网上的解释有很多,但我看见的只有一个。就是我的第三个类。你只要复制全了代码,我想是不会有问题的。

如何使用Java发送qq邮件

方法:

  1. 前提准备工作: 首先,邮件的发送方要开启POP3 和SMTP服务--即发送qq邮件的账号要开启POP3 和SMTP服务
  2. 开启方法: 登陆qq邮箱
  3. 点击 设置
  4. 点击—-账户
  5. 找到:POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务 —点击开启
  6. 送短信 —–点击确定
  7. 稍等一会,很得到一个授权码! –注意:这个一定要记住,一会用到
  8. 点击保存修改 —OK 完成
  9. java 测试代码:
package cn.cupcat.test;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class SendmailUtil {
    public static void main(String[] args) throws AddressException, MessagingException {
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");// 连接协议
        properties.put("mail.smtp.host", "smtp.qq.com");// 主机名
        properties.put("mail.smtp.port", 465);// 端口号
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.ssl.enable", "true");//设置是否使用ssl安全连接 ---一般都使用
        properties.put("mail.debug", "true");//设置是否显示debug信息 true 会在控制台显示相关信息
        //得到回话对象
        Session session = Session.getInstance(properties);
        // 获取邮件对象
        Message message = new MimeMessage(session);
        //设置发件人邮箱地址
        message.setFrom(new InternetAddress("123456789@qq.com"));
        //设置收件人地址 message.setRecipients( RecipientType.TO, new InternetAddress[] { new InternetAddress("987654321@qq.com") });
        //设置邮件标题
        message.setSubject("这是第一封Java邮件");
        //设置邮件内容
        message.setText("内容为: 这是第一封java发送来的邮件。");
        //得到邮差对象
        Transport transport = session.getTransport();
        //连接自己的邮箱账户
        transport.connect("123456789@qq.com", "vvctybgbvvophjcj");//密码为刚才得到的授权码
        //发送邮件 transport.sendMessage(message, message.getAllRecipients());
    }
}

10.运行就会发出邮件了。。。。 下面是我收到邮件的截图,当然我把源码中的邮件地址都是修改了,不是真实的,你们测试的时候,可以修改能你们自己的邮箱。最后,祝你也能成功,如果有什么问题,可以一起讨论! 注意事项 得到的授权码一定要保存好,程序中要使用

Java收发邮件过程中具体的功能是怎么实现的

  1. SMTP协议 用户连上邮件服务器后,要想给它发送一封电子邮件,需要遵循一定的通迅规则,SMTP协议就是用于定义这种通讯规则的。 因而,通常我们也把处理用户smtp请求(邮件发送请求)的邮件服务器称之为SMTP服务器。(25)
  2. POP3协议 同样,用户若想从邮件服务器管理的电子邮箱中接收一封电子邮件的话,他连上邮件服务器后,也需要遵循一定的通迅格式,POP3协议用于定义这种通讯格式。 因而,通常我们也把处理用户pop3请求(邮件接收请求)的邮件服务器称之为POP3服务器。(110) 下图用于演示两帐户相互发送邮件的过程 3.1 JavaMail API按其功能划分通常可分为如下三大类:
  • 创建和解析邮件内容的API :Message类是创建和解析邮件的核心API,它的实例对象代表一封电子邮件。
  • 3.2 发送邮件的API:Transport类是发送邮件的核心API类,它的实例对象代表实现了某个邮件发送协议的邮件发送对象,例如SMTP协议。
  • 接收邮件的API:Store类是接收邮件的核心API类,它的实例对象代表实现了某个邮件接收协议的邮件接收对象,例如POP3协议。 3.3 Session类 Session类用于定义整个应用程序所需的环境信息,以及收集客户端与邮件服务器建立网络连接的会话信息,如邮件服务器的主机名、端口号、采用的邮件发送和接收协议等。Session对象根据这些信息构建用于邮件收发的Transport和Store对象,以及为客户端创建Message对象时提供信息支持。
  1. 邮件组织结构相关的API
  • MimeMessage类表示整封邮件。
  • MimeBodyPart类表示邮件的一个MIME消息。
  • MimeMultipart类表示一个由多个MIME消息组合成的组合MIME消息。
  1. 具体的例子程序
package cn.edu.dlmu.send;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class SendMail {
    public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        //连接的邮件服务器的主机名
        prop.setProperty("mail.smtp.host", "smtp.sina.com.cn");
        //发送邮件的协议
        prop.setProperty("mail.transport.protocol", "smtp");
        //是否向邮件服务器提交认证
        prop.setProperty("mail.smtp.auth", "true");
        //创建session
        Session session = Session.getInstance(prop);
        session.setDebug(true);
        //得到transport
        Transport ts = session.getTransport();
        //连接邮件服务器
        ts.connect("smtp.sina.com.cn", "xxxx@sina.com", "xxxxx");
        //发送邮件
        MimeMessage message = createMessage(session);
        ts.sendMessage(message, message.getAllRecipients());
        ts.close();
    }
    public static MimeMessage createMessage(Session session) throws Exception {
        MimeMessage message = new MimeMessage(session);
        //设置邮件的基本信息
        message.setFrom(new InternetAddress("xxxx@sina.com"));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress("1219070362@qq.com"));
        message.setSubject("test");
        //正文
        MimeBodyPart text = new MimeBodyPart();
        //设置charaset可以解决中文正文的乱码问题,内嵌可下载的图片
        text.setContent("你好xxx,<img src='c:/dog.jpg' />测试成功!<br/><img src='cid:aaa.jpg' />", "text/html;charset=gbk");
        //图片1
        MimeBodyPart image = new MimeBodyPart();
        image.setDataHandler(new DataHandler(new FileDataSource("src/88.jpg")));
        image.setContentID("aaa.jpg");
        //附件
        MimeBodyPart attach = new MimeBodyPart();
        DataHandler dh = new DataHandler(new FileDataSource("src/javamail架包.jar"));
        attach.setDataHandler(dh);
        //解决文件中文乱码问题
        attach.setFileName(MimeUtility.encodeText(dh.getName()));
        //描述正文和图片的关系
        MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(text);
        mp.addBodyPart(image);
        mp.setSubType("related");
        //描述正文和附件
        MimeMultipart mp2 = new MimeMultipart();
        mp2.addBodyPart(attach);
        //将正文封装为一个body
        MimeBodyPart content = new MimeBodyPart();
        content.setContent(mp);
        mp2.addBodyPart(content);
        mp2.setSubType("mixed");
        message.setContent(mp2);
        message.saveChanges();
        return message;
    }
}