java發送郵件的原始碼

來源:互聯網
上載者:User

package com.test.mail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
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;

public class SendMail {
 public static void main(String[] args) {
  try {
   String username="source@163.com";
   String password="xxxxx";
   String smtp_server="smtp.163.com";
   String from_mail_address=username;
   String to_mail_address="to@163.com";
   
   Authenticator auth = new PopupAuthenticator(username,password);

   Properties mailProps = new Properties();
   mailProps.put("mail.smtp.auth", "true");

   mailProps.put("username", username);

   mailProps.put("password", password);

   mailProps.put("mail.smtp.host", smtp_server);
   Session mailSession = Session.getDefaultInstance(mailProps, auth);
   MimeMessage message = new MimeMessage(mailSession);
   message.setFrom(new InternetAddress(from_mail_address));
   message.setRecipient(Message.RecipientType.TO, new InternetAddress(to_mail_address));
   message.setSubject("Mail Test");

   MimeMultipart multi = new MimeMultipart();
   BodyPart textBodyPart = new MimeBodyPart();
   textBodyPart.setText("電子郵件測試內容!");
   multi.addBodyPart(textBodyPart);
   message.setContent(multi);
   message.saveChanges();
   Transport.send(message);
  } catch (Exception ex) {
   System.err.println("郵件發送失敗的原因是:" + ex.getMessage());
   System.err.println("具體錯誤原因:");
   ex.printStackTrace(System.err);
  }
 }

}

class PopupAuthenticator extends Authenticator {
 private String username;
 private String password;
 public PopupAuthenticator(String username,String password){
  this.username=username;
     this.password=password;
 }
 public PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication(this.username, this.password);
 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.