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

发送电子邮件

—— 发送E

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

631
发送电子邮件

import java.util.Properties;


import javax.mail.Authenticator;

import javax.mail.Message;/* 来 自 N o w J a v a . c o m - 时  代  Java*/

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 Main {


  public static void main(String[] args) {


    Properties properties = new Properties();

    properties.put("mail.smtp.host", "smtp.somewhere.com");/*来自 N o w J a v a . c o m*/

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


    Session session = Session.getDefaultInstance(properties,

        new MessageAuthenticator("username", "password"));


    Message message = new MimeMessage(session);

    try {

      message.setFrom(new InternetAddress("someone@somewhere.com"));

      message.setRecipient(Message.RecipientType.TO, new InternetAddress(

          "someone@somewhere.com"));

      message.setSubject("Subject");

      message.setContent("This is a test message", "text/plain");

      Transport.send(message);

    } catch (MessagingException e) {

      e.printStackTrace();

    }

  }


}


class MessageAuthenticator extends Authenticator {

  PasswordAuthentication authentication = null;
展开阅读全文