集册 Java实例教程 发送电子邮件

发送电子邮件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

424
发送电子邮件
/*
时   代     Java  公  众  号 - nowjava.com
*/


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;

import java.util.Properties;


public class Main{

    public static void main(String[] argv) throws Exception{

        String addressee = "nowjava.com";//时代Java - nowjava.com 提 供

        String text = "nowjava.com";

        sendAnEmail(addressee,text);

    }

    public static void sendAnEmail(String addressee, String text) {

        final String username = "test@gmail.com";

        final String password = "krvplvfllizmeklu";


        Properties props = new Properties();

        props.put("mail.smtp.auth", "true");

        props.put("mail.smtp.starttls.enable", "true");

        props.put("mail.smtp.host", "smtp.gmail.com");

        props.put("mail.smtp.port", "587");


        Session session = Session.getInstance(props,

                new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {

                        return new PasswordAuthentication(username,

                                password);

                    }

                });


        try {

            Message message = new MimeMessage(session);

            message.setFrom(new InternetAddress("test@gmail.com"));

            message.setRecipients(Message.RecipientType.TO,

                    InternetAddress.parse(addressee));

            message.setSubject("Happy hours in McDonalds");

        
展开阅读全文