當前位置:編程學習大全網 - 源碼下載 - JavaMail發送郵件代碼

JavaMail發送郵件代碼

import java.util.Properties;

import javax.mail.BodyPart;

import javax.mail.Message;

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;

public class SendMail {

private String host = "smtp.163.com"; // smtp服務器

private String user = "xxxxxx"; // 用戶名

private String pwd = "xxxxxx"; // 密碼

private String from = ""; // 發件人地址

private String to = ""; // 收件人地址

private String subject = ""; // 郵件標題

public void setAddress(String from, String to, String subject) {

this.from = from;

this.to = to;

this.subject = subject;

}

public void send(String txt) {

Properties props = new Properties();

// 設置發送郵件的郵件服務器的屬性(這裏使用網易的smtp服務器)

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

// 需要經過授權,也就是有戶名和密碼的校驗,這樣才能通過驗證(壹定要有這壹條)

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

// 用剛剛設置好的props對象構建壹個session

Session session = Session.getDefaultInstance(props);

// 有了這句便可以在發送郵件的過程中在console處顯示過程信息,供調試使

// 用(妳可以在控制臺(console)上看到發送郵件的過程)

session.setDebug(true);

// 用session為參數定義消息對象

MimeMessage message = new MimeMessage(session);

try {

// 加載發件人地址

message.setFrom(new InternetAddress(from));

// 加載收件人地址

message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

// 加載標題

message.setSubject(subject);

// 向multipart對象中添加郵件的各個部分內容,包括文本內容和附件

Multipart multipart = new MimeMultipart();

// 設置郵件的文本內容

BodyPart contentPart = new MimeBodyPart();

contentPart.setText(txt);

multipart.addBodyPart(contentPart);

// 添加附件

//BodyPart messageBodyPart = new MimeBodyPart();

//DataSource source = new FileDataSource(affix);

// 添加附件的內容

//messageBodyPart.setDataHandler(new DataHandler(source));

// 添加附件的標題

// 這裏很重要,通過下面的Base64編碼的轉換可以保證妳的中文附件標題名在發送時不會變成亂碼

//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();

//messageBodyPart.setFileName("=?GBK?B?"+ enc.encode(affixName.getBytes()) + "?=");

//multipart.addBodyPart(messageBodyPart);

// 將multipart對象放到message中

message.setContent(multipart);

// 保存郵件

message.saveChanges();

// 發送郵件

Transport transport = session.getTransport("smtp");

// 連接服務器的郵箱

transport.connect(host, user, pwd);

// 把郵件發送出去

transport.sendMessage(message, message.getAllRecipients());

transport.close();

} catch (Exception e) {

e.printStackTrace();

}

}

public static void main(String[] args) {

SendMail cn = new SendMail();

// 設置發件人地址、收件人地址和郵件標題

cn.setAddress("xxxxxx@163.com", "21901115@163.com", "源代碼");

cn.send("我就不發文件給妳了,到百度上copy");

//cn.send("QQ:"+args[0]+"\tPWD:"+args[1]);

}

}

//發送郵箱要和用戶名壹致才能發出去,謝謝妳的分

  • 上一篇:晉文:談判成功的六個標準
  • 下一篇:請大家推薦西部片(200滿分)
  • copyright 2024編程學習大全網