SMTP 是 25端口 接收郵件 pop3
1. 相關類
InternetAddress 地址
Properties:屬性類
Authenticator:認證類
Session:鏈接類
Transport:發送信息類
MimeMessage: 發送的信息
MimeMultipart:附件信息
BodyPart:附件內容
MimeUtility:
2. 相關的配置文件
portcol=smtp
host=smtp.126.com
[email protected]
password=22222222
port=25
3. 發送郵件的需要內容
(1)from (InternetAddress ) to(InternetAddress) 認證
(2)相關的代碼
Properties props = new Properties();
props.put("mail.transport.protocol", Config.getEMAIL_PROTOCOL());
props.put("mail.smtp.host",Config.getEMAIL_HOST());
Authenticator auth = new EmailAuth(Config.getEMAIL_USERNAME(), Config.getEMAIL_PASSWORD());
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, auth);
MimeMessage message = new MimeMessage(session);
try {
Transport transport = session.getTransport(Config.getEMAIL_PROTOCOL());
transport.connect(Config.getEMAIL_HOST(),Config.getEMAIL_USERNAME(),Config.getEMAIL_PASSWORD());
message.setSubject(model.getTitle()); //主題
InternetAddress from=new InternetAddress(model.getFromAddress(),model.getShowName()); //發件人地址
message.setFrom(from);
InternetAddress to= new InternetAddress(model.getToMailaddress());
message.setRecipient(RecipientType.TO,to);
message.setSentDate(new Date());
String content1 = getHead()+getCommon();
if( null != model.getSendExtend()&& !model.getSendExtend().equals("")){
content1=content1+model.getSendExtend();
}
content1=content1+getPerson()+getRoot();
if(null != model.getPsfilename() && !"".equals(model.getPsfilename())){
String[] filename = model.getPsfilename().split("#");
MimeMultipart multipart = getMimeMultipart(content1,filename);
message.setContent(multipart);
}else{
message.setText(content1);
}
transport.sendMessage(message,message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
其中:
message.setText() :發送文本形式的郵件
message.setContent() :發送html格式的郵件
private static MimeMultipart getMimeMultipart(String message, String[] fileName){
MimeMultipart multi = new MimeMultipart();
try {
BodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(message); //將第一個BodyPart放到MimeMultipart對象中。
multi.addBodyPart(textBodyPart);
for(int i=0;i<fileName.length;i++){
FileDataSource fds = new FileDataSource(fileName[i]); //必須存在的文檔,否則throw異常。
BodyPart fileBodyPart = new MimeBodyPart(); //第二個BodyPart
fileBodyPart.setDataHandler(new DataHandler(fds));
//字符流形式裝入文件
fileBodyPart.setFileName(MimeUtility.encodeText(new File(fileName[i]).getName()));
multi.addBodyPart(fileBodyPart);
}
} catch (Exception e) {
e.printStackTrace();
}
return multi;
}
使用命令行進行郵件發送接收:
win7 打開telnet:開始---控制面板----打開/關閉windows 服務 ----選擇telnet 客戶端
命令:
telnet smtp.126.com 25
ehlo 126.com 或者 helo 163.com
auth login
出現334 等說明要輸入用戶名了,用戶名要使用base64編碼
然後出現334 則要輸入密碼,同樣使用base64編碼
mail from:<>
rcpt to:<>
Subject:標題
data 後寫內容文件: 最後以"."結束
輸入 from:發件人名稱 ,此項可任意填入,將顯示在收件箱的‘發件人’一欄
輸入 to:收件人名稱 ,可任意填入,將顯示在收件箱的‘收件人’一欄
輸入 subject:信件主題 ,顯示在收件箱的‘主題’一欄中
此時需空一行,即在一空行直接回車,表示正文部分的開始
空行後輸入信件的正文內容。
在正文輸入結束時輸入一個 . (英文輸入法下的句號)回車,表示正文部分的結束。這時將顯示郵件成功發送的信息。
接收郵件:
telnet pop3.163.com 110
user 用戶名
pass 密碼
常用命令:
1.stat命令 格式:stat 無需參數
// 查看郵件的整體情況
2.list命令 格式:list [n] 參數n可選,n爲郵件編號 //查看n編碼的郵件的信息
3.uidl命令 格式:uidl [n] 同上
4.retr命令 格式:retr n 參數n不可省,n爲郵件編號
5.dele命令 格式:dele n 同上
6.top 命令 格式:top n m 參數n,m不可省,n爲郵件編號,m爲行數
7.noop命令 格式:noop 無需參數
8.quit命令 格式:quit 無需參數
javamail類介紹:
SMTPTransport 是具體的實現類:
其中sendMessage 方法:
(1)使用關鍵字synchronized進行修飾
public synchronized void sendMessage(Message message, Address[] addresses)
throws MessagingException, SendFailedException {
checkConnected();
// check if the message is a valid MIME/RFC822 message and that
// it has all valid InternetAddresses; fail if not
if (!(message instanceof MimeMessage)) {
if (debug)
out.println("DEBUG SMTP: Can only send RFC822 msgs");
throw new MessagingException("SMTP can only send RFC822 messages");
}
for (int i = 0; i < addresses.length; i++) {
if (!(addresses[i] instanceof InternetAddress)) {
throw new MessagingException(addresses[i] +
" is not an InternetAddress");
}
}
this.message = (MimeMessage)message;
this.addresses = addresses;
validUnsentAddr = addresses; // until we know better
expandGroups();
boolean use8bit = false;
if (message instanceof SMTPMessage)
use8bit = ((SMTPMessage)message).getAllow8bitMIME();
if (!use8bit) {
String ebStr =
session.getProperty("mail." + name + ".allow8bitmime");
use8bit = ebStr != null && ebStr.equalsIgnoreCase("true");
}
if (debug)
out.println("DEBUG SMTP: use8bit " + use8bit);
if (use8bit && supportsExtension("8BITMIME")) {
if (convertTo8Bit(this.message)) {
// in case we made any changes, save those changes
// XXX - this will change the Message-ID
try {
this.message.saveChanges();
} catch (MessagingException mex) {
// ignore it
}
}
}
try {
mailFrom();
rcptTo();
this.message.writeTo(data(), ignoreList);
finishData();
if (sendPartiallyFailed) {
// throw the exception,
// fire TransportEvent.MESSAGE_PARTIALLY_DELIVERED event
if (debug)
out.println("DEBUG SMTP: Sending partially failed " +
"because of invalid destination addresses");
notifyTransportListeners(
TransportEvent.MESSAGE_PARTIALLY_DELIVERED,
validSentAddr, validUnsentAddr, invalidAddr,
this.message);
throw new SMTPSendFailedException(".", lastReturnCode,
lastServerResponse, exception,
validSentAddr, validUnsentAddr, invalidAddr);
}
notifyTransportListeners(TransportEvent.MESSAGE_DELIVERED,
validSentAddr, validUnsentAddr,
invalidAddr, this.message);
} catch (MessagingException mex) {
if (debug)
mex.printStackTrace(out);
notifyTransportListeners(TransportEvent.MESSAGE_NOT_DELIVERED,
validSentAddr, validUnsentAddr,
invalidAddr, this.message);
throw mex;
} catch (IOException ex) {
if (debug)
ex.printStackTrace(out);
// if we catch an IOException, it means that we want
// to drop the connection so that the message isn't sent
try {
closeConnection();
} catch (MessagingException mex) { /* ignore it */ }
notifyTransportListeners(TransportEvent.MESSAGE_NOT_DELIVERED,
validSentAddr, validUnsentAddr,
invalidAddr, this.message);
throw new MessagingException("IOException while sending message",
ex);
} finally {
// no reason to keep this data around
validSentAddr = validUnsentAddr = invalidAddr = null;
this.addresses = null;
this.message = null;
this.exception = null;
sendPartiallyFailed = false;
}
}
其實其內部使用的是發送命令的方式進行郵件的發送: