天天看点

Java中jmail发送邮件

package com.zhx;

import java.util.Properties;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.PasswordAuthentication;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

public class Mail

{

    public static void main(String[] args)

    {

        String mailForm = "zzz";//发出邮件的地址

        String passWord = "xxx";//发出邮件的密码

        String host = "smtp.163.com";//发送邮件的服务器地址,以163邮箱为例,服务器地址为smtp.163.com

        String mailTo = "vvv";//发送邮件的地址

        //发送邮件的内容

        String content = "asdf";

        // 创建一个配置文件并保存

        Properties properties = new Properties();

        // 发送服务器需要身份验证,有些可能会存在没有密码的情况,可以设置为false,不进行密码校验

        properties.setProperty("mail.smtp.auth", "true");

        // 设置邮件服务器主机名

        properties.setProperty("mail.host", host);

        // 发送邮件协议名称

        properties.setProperty("mail.transport.protocol", "smtp");

        try

        {

            // 设置环境信息

            Session localSession = Session.getInstance(properties, new javax.mail.Authenticator() {

                // 在session中设置账户信息,Transport发送邮件时会使用

                protected PasswordAuthentication getPasswordAuthentication()

                {

                    return new PasswordAuthentication(mailForm, passWord);

                }

            });

            // 创建邮件对象

            Message msg = new MimeMessage(localSession);

            // 发件人

            msg.setFrom(new InternetAddress(mailForm));

            // 收件人

            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTo));

            // 主题

            msg.setSubject("qwer");

            // HTML内容

            msg.setContent(content, "text/html;charset=utf-8");

            Transport.send(msg);

        }

        catch (MessagingException e)

        {

            e.printStackTrace();

        }

    }

}

以上为jmail依赖发送邮件的代码

继续阅读