Bạn muốn gửi một mail có kèm theo file nhưng chưa biết cách viết code cho nó như thế nào. Sau đây là doạn code giúp bạn làm được điều đó.
import java.io.*;
import java.net.*;
public class testMailMIME
{
static int SMTPport = 25;
static Socket socket;
static DataInputStream in;
static DataOutputStream out;
static PrintStream prout;
/* Tên file sẽ được gửi */
String FileName = "gumby.gif";
public static void main(String s[])
{
/*
** testMAILMIME [server] [destinataire]
*/
testMailMIME t = new testMailMIME();
t.sendMail(s[0], s[1]);
}
public void sendMail(String mailServer, String recipient)
{
System.out.println("Send mail with attached file");
try
{
Socket s = new Socket(mailServer, 25);
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream(), "8859_1"));
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(s.getOutputStream(),
"8859_1"));
String boundary = "DataSeparatorString";
// Giả sử lúc này bạn đã gửi username
sendln(in, out, "HELO theWorld");
// Cảnh báo: một số mail server có kiểm chứng địa chỉ gửi
// trong lệnh FROM command, đặt địa chỉ thật sự ở đây
sendln(in, out,
"MAIL FROM: <Elvis.Presley@jailhouse.rock>");
sendln(in, out, "RCPT TO: <" + recipient + ">" );
// Nếu có hơn 1 người nhận thì lặp lại các câu lệnh sau
// sendln(in, out, "RCPT TO: <" + recipient2 + ">" );
// sendln(in, out, "RCPT TO: <" + recipient3 + ">" );
// ...
sendln(in, out, "DATA");
sendln(out, "MIME-Version: 1.0");
sendln(out, "Subject: remember me");
sendln(out,
"From: Elvis Presley <Elvis.Presley@jailhouse.rock>");
sendln(out,
"Content-Type: multipart/mixed; boundary=\"" +
boundary + "\"");
sendln(out, "\r\n--" + boundary);
// Gửi nội dung
sendln(out,
"Content-Type: text/plain; charset=\"us-ascii\"\r\n");
sendln(out, "I'm alive. Help me!\r\n\r\n");
sendln(out, "\r\n--" + boundary );
// Gửi file
sendln(out, "Content-Type:image/gif; name=" + FileName);
sendln(out,
"Content-Disposition: attachment;filename=\"" + FileName + "\"");
sendln(out, "Content-transfer-encoding: base64\r\n");
MIMEBase64.encode(FileName, out);
sendln(out, "\r\n--" + boundary);
sendln(out, "\r\n\r\n--" + boundary + "--\r\n");
sendln(in, out, ".");
sendln(in, out, "QUIT");
s.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void sendln( BufferedReader in, BufferedWriter out, String s)
{
try
{
out.write(s + "\r\n");
out.flush();
// System.out.println(s);
s = in.readLine();
// System.out.println(s);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void sendln(BufferedWriter out, String s)
{
try
{
out.write(s + "\r\n");
out.flush();
System.out.println(s);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Class MIMEBase64:
import java.io.*;
public class MIMEBase64
{
/*********************************************************
** Base64 sử dụng tập hợp ký tự con 65 của bảng mã US-ASCII,
** Cho phép 1 ký tự được mã hóa chỉ với 6 bits, vì vậy ký tự
** "m" với Base64 có giá trị 38, khi chuyển sang dạng nhị phân
** là 100110.
**
** Với chuỗi ký tự, giả sử "men" được mã hóa, sẽ xảy ra điều gì:
** Chuỗi được chuyển sang giá trị US-ASCII của nó.
**
** Ký tự "m" có giá trị thập phân là 109
** Ký tự "e" có giá trị thập phân là 101
** Ký tự "n" có giá trị thập phân là 110
**
** Khi chuyển sang dạng nhị phân nó có dạng sau:
**
** m 01101101
** e 01100101
** n 01101110
**
** 3 ký tự "8-bits" được nối vói nhau để tạo thành dòng 24 bits
** 011011010110010101101110
**
** Dòng 24 bit này sau đó được chia sang 4 phần 6-bit
** 011011 010110 010101 101110
**
** Bây giờ chúng ta có 4 giá trị. Những gí trị nhị phân này
** được chuyển sang dạng thập phân:
** 27 22 21 46
**
** Và tương ứng với các ký tự Base64:
** b W V u
**
** Mã hóa luôn dựa trên 3 ký tự
** (Để có một tập hợp các ký tự Base64). Để mã hóa 1 hoặc 2 ký
** tự, chúng ta sử dụng ký tự đặc biệt "=" để thêm vào cho đến
** khi đủ 4 ký tự base64
** Ví dụ. encode "me"
**
** 01101101 01100101
** 0110110101100101
** 011011 010110 0101
** 111111 (để thêm vào các bits bị bỏ lỡ)
** 011011 010110 010100
** b W U
** b W U = ("=" là ký tự thêm vào)
**
** vì thế "bWU=" tương ứng với mã hóa Base64.
**
** encode "m"
**
** 01101101
** 011011 01
** 111111
** 011011 010000
** b Q = = (2 ký tự được thêm vào)
**/
static String BaseTable[] =
{
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O",
"P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d",
"e","f","g","h","i","j","k","l","m","n","o","p","q","r","s",
"t","u","v","w","x","y","z","0","1","2","3","4","5","6","7",
"8","9","+","/"
};
public static void encode(String filename, BufferedWriter out)
{
try
{
File f = new File(filename);
FileInputStream fin = new FileInputStream(filename);
// Đọc toàn bộ file sang mảng byte
byte bytes[] = new byte[(int)(f.length())];
int n = fin.read(bytes);
// Không có bytes nào được mã hóa!?!
if (n < 1) return;
// Mảng của những ký tự base64
byte buf[] = new byte[4];
int n3byt = n / 3; // Nhóm 3 byte
int nrest = n % 3; // Những byte còn lại từ nhóm
int k = n3byt * 3;
int linelength = 0;
int i = 0;
// Tạo nhóm 3 byte...
while ( i < k )
{
buf[0] = (byte)(( bytes & 0xFC) >> 2);
buf[1] = (byte)(((bytes & 0x03) << 4) |
((bytes[i+1] & 0xF0) >> 4));
buf[2] = (byte)(((bytes[i+1] & 0x0F) << 2) |
((bytes[i+2] & 0xC0) >> 6));
buf[3] = (byte)( bytes[i+2] & 0x3F);
send(out, BaseTable[buf[0]]);
send(out, BaseTable[buf[1]]);
send(out, BaseTable[buf[2]]);
send(out, BaseTable[buf[3]]);
/*****************************************************
** Đoạn mã trên có thể được viết theo cách tối ưu hơn.
** Tuy khó hiểu nhưng gọn hơn.
**
** buf[0]= (byte)(b >> 2);
** buf[1]= (byte)(((b & 0x03) << 4)|(b[i+1]>> 4));
** buf[2]= (byte)(((b[i+1] & 0x0F)<< 2)|(b[i+2]>> 6));
** buf[3]= (byte)(b[i+2] & 0x3F);
** send(out, BaseTable[buf[0]] + BaseTable[buf[1]] +
** BaseTable[buf[2]] + BaseTable[buf[3]]);
**/
if ((linelength += 4) >= 76)
{
send(out, "\r\n");
linelength = 0;
}
i += 3;
}
// Các ký tự thêm vào...
if (nrest == 2)
{
// 2 bytes còn lại
buf[0] = (byte)(( bytes[k] & 0xFC) >> 2);
buf[1] = (byte)(((bytes[k] & 0x03) << 4) |
((bytes[k+1] & 0xF0) >> 4));
buf[2] = (byte)(( bytes[k+1] & 0x0F) << 2);
}
else if (nrest == 1)
{
// 1 byte còn lại
buf[0] = (byte)((bytes[k] & 0xFC) >> 2);
buf[1] = (byte)((bytes[k] & 0x03) << 4);
}
if (nrest > 0)
{
// Gửi ký tự thêm vào
if ((linelength += 4) >= 76)
send(out, "\r\n");
send(out, BaseTable[buf[0]]);
send(out, BaseTable[buf[1]]);
if (nrest == 2)
{
send(out, BaseTable[buf[2]]);
}
else
{
send(out, "=");
}
send(out, "=");
}
out.flush();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void send(BufferedWriter out, String s)
{
try
{
out.write(s);
System.out.print(s);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Nếu muốn gửi file gif và file text, bạn phải thay đổi hàm sendMail() lại một chút.
...
/* Tên của các file được gửi. */
String FileName1 = "gumby.gif";
String FileName2 = "gumby.txt";
...
public void sendMail(String mailServer, String recipient)
{
System.out.println("Send mail with attached file");
try
{
Socket s = new Socket(mailServer, 25);
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream(), "8859_1"));
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(s.getOutputStream(),"8859_1"));
String boundary = "DataSeparatorString";
// Giả sử lúc này bạn đã gửi username
sendln(in, out, "HELO world");
sendln(in, out, "MAIL FROM: <real@gagnon.com>");
sendln(in, out, "RCPT TO: <" + recipient + ">" );
sendln(in, out, "DATA");
sendln(out, "MIME-Version: 1.0");
sendln(out, "Subject: remember me");
sendln(out,
"From: Elvis Presley <Elvis.Presley@jailhouse.rock<");
sendln(out,
"Content-Type: multipart/mixed; boundary=\"" +
boundary + "\"");
sendln(out, "\r\n--" + boundary);
// Gửi file GIF
sendln(out,
"Content-Type: text/plain; charset=\"us-ascii\"\r\n");
sendln(out, "I'm alive. Help me!\n\n");
sendln(out, "\r\n" + "--" + boundary );
sendln(out, "Content-Type:image/gif; name=" + FileName1);
sendln(out, "Content-Disposition: attachment;filename=\"" +
FileName1 + "\"");
sendln(out, "Content-transfer-encoding: base64\r\n");
MIMEBase64.encode(FileName1, out);
sendln(out, "\r\n--" + boundary);
// File text
sendln(out, "Content-Type: text/plain; name=" + FileName2);
sendln(out, "Content-Disposition: inline;filename=\"" + FileName2 + "\"");
// Để gửi kèm file thay vì gửi trong mail:
// sendln(out, "Content-Type: text/plain; name=" +
// FileName2);
// sendln(out,
// "Content-Disposition: attachment;filename=\""+
// FileName2+"\"");
sendln(out, "Content-Transfer-Encoding: base64\r\n");
MIMEBase64.encode(FileName2, out);
sendln(out, "\r\n\r\n--" + boundary + "--\r\n");
// ok
sendln(in, out,".");
sendln(in, out, "QUIT");
s.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
...
Trích từ “Thủ thuật lập trình Java“
import java.io.*;
import java.net.*;
public class testMailMIME
{
static int SMTPport = 25;
static Socket socket;
static DataInputStream in;
static DataOutputStream out;
static PrintStream prout;
/* Tên file sẽ được gửi */
String FileName = "gumby.gif";
public static void main(String s[])
{
/*
** testMAILMIME [server] [destinataire]
*/
testMailMIME t = new testMailMIME();
t.sendMail(s[0], s[1]);
}
public void sendMail(String mailServer, String recipient)
{
System.out.println("Send mail with attached file");
try
{
Socket s = new Socket(mailServer, 25);
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream(), "8859_1"));
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(s.getOutputStream(),
"8859_1"));
String boundary = "DataSeparatorString";
// Giả sử lúc này bạn đã gửi username
sendln(in, out, "HELO theWorld");
// Cảnh báo: một số mail server có kiểm chứng địa chỉ gửi
// trong lệnh FROM command, đặt địa chỉ thật sự ở đây
sendln(in, out,
"MAIL FROM: <Elvis.Presley@jailhouse.rock>");
sendln(in, out, "RCPT TO: <" + recipient + ">" );
// Nếu có hơn 1 người nhận thì lặp lại các câu lệnh sau
// sendln(in, out, "RCPT TO: <" + recipient2 + ">" );
// sendln(in, out, "RCPT TO: <" + recipient3 + ">" );
// ...
sendln(in, out, "DATA");
sendln(out, "MIME-Version: 1.0");
sendln(out, "Subject: remember me");
sendln(out,
"From: Elvis Presley <Elvis.Presley@jailhouse.rock>");
sendln(out,
"Content-Type: multipart/mixed; boundary=\"" +
boundary + "\"");
sendln(out, "\r\n--" + boundary);
// Gửi nội dung
sendln(out,
"Content-Type: text/plain; charset=\"us-ascii\"\r\n");
sendln(out, "I'm alive. Help me!\r\n\r\n");
sendln(out, "\r\n--" + boundary );
// Gửi file
sendln(out, "Content-Type:image/gif; name=" + FileName);
sendln(out,
"Content-Disposition: attachment;filename=\"" + FileName + "\"");
sendln(out, "Content-transfer-encoding: base64\r\n");
MIMEBase64.encode(FileName, out);
sendln(out, "\r\n--" + boundary);
sendln(out, "\r\n\r\n--" + boundary + "--\r\n");
sendln(in, out, ".");
sendln(in, out, "QUIT");
s.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void sendln( BufferedReader in, BufferedWriter out, String s)
{
try
{
out.write(s + "\r\n");
out.flush();
// System.out.println(s);
s = in.readLine();
// System.out.println(s);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void sendln(BufferedWriter out, String s)
{
try
{
out.write(s + "\r\n");
out.flush();
System.out.println(s);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Class MIMEBase64:
import java.io.*;
public class MIMEBase64
{
/*********************************************************
** Base64 sử dụng tập hợp ký tự con 65 của bảng mã US-ASCII,
** Cho phép 1 ký tự được mã hóa chỉ với 6 bits, vì vậy ký tự
** "m" với Base64 có giá trị 38, khi chuyển sang dạng nhị phân
** là 100110.
**
** Với chuỗi ký tự, giả sử "men" được mã hóa, sẽ xảy ra điều gì:
** Chuỗi được chuyển sang giá trị US-ASCII của nó.
**
** Ký tự "m" có giá trị thập phân là 109
** Ký tự "e" có giá trị thập phân là 101
** Ký tự "n" có giá trị thập phân là 110
**
** Khi chuyển sang dạng nhị phân nó có dạng sau:
**
** m 01101101
** e 01100101
** n 01101110
**
** 3 ký tự "8-bits" được nối vói nhau để tạo thành dòng 24 bits
** 011011010110010101101110
**
** Dòng 24 bit này sau đó được chia sang 4 phần 6-bit
** 011011 010110 010101 101110
**
** Bây giờ chúng ta có 4 giá trị. Những gí trị nhị phân này
** được chuyển sang dạng thập phân:
** 27 22 21 46
**
** Và tương ứng với các ký tự Base64:
** b W V u
**
** Mã hóa luôn dựa trên 3 ký tự
** (Để có một tập hợp các ký tự Base64). Để mã hóa 1 hoặc 2 ký
** tự, chúng ta sử dụng ký tự đặc biệt "=" để thêm vào cho đến
** khi đủ 4 ký tự base64
** Ví dụ. encode "me"
**
** 01101101 01100101
** 0110110101100101
** 011011 010110 0101
** 111111 (để thêm vào các bits bị bỏ lỡ)
** 011011 010110 010100
** b W U
** b W U = ("=" là ký tự thêm vào)
**
** vì thế "bWU=" tương ứng với mã hóa Base64.
**
** encode "m"
**
** 01101101
** 011011 01
** 111111
** 011011 010000
** b Q = = (2 ký tự được thêm vào)
**/
static String BaseTable[] =
{
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O",
"P","Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d",
"e","f","g","h","i","j","k","l","m","n","o","p","q","r","s",
"t","u","v","w","x","y","z","0","1","2","3","4","5","6","7",
"8","9","+","/"
};
public static void encode(String filename, BufferedWriter out)
{
try
{
File f = new File(filename);
FileInputStream fin = new FileInputStream(filename);
// Đọc toàn bộ file sang mảng byte
byte bytes[] = new byte[(int)(f.length())];
int n = fin.read(bytes);
// Không có bytes nào được mã hóa!?!
if (n < 1) return;
// Mảng của những ký tự base64
byte buf[] = new byte[4];
int n3byt = n / 3; // Nhóm 3 byte
int nrest = n % 3; // Những byte còn lại từ nhóm
int k = n3byt * 3;
int linelength = 0;
int i = 0;
// Tạo nhóm 3 byte...
while ( i < k )
{
buf[0] = (byte)(( bytes & 0xFC) >> 2);
buf[1] = (byte)(((bytes & 0x03) << 4) |
((bytes[i+1] & 0xF0) >> 4));
buf[2] = (byte)(((bytes[i+1] & 0x0F) << 2) |
((bytes[i+2] & 0xC0) >> 6));
buf[3] = (byte)( bytes[i+2] & 0x3F);
send(out, BaseTable[buf[0]]);
send(out, BaseTable[buf[1]]);
send(out, BaseTable[buf[2]]);
send(out, BaseTable[buf[3]]);
/*****************************************************
** Đoạn mã trên có thể được viết theo cách tối ưu hơn.
** Tuy khó hiểu nhưng gọn hơn.
**
** buf[0]= (byte)(b >> 2);
** buf[1]= (byte)(((b & 0x03) << 4)|(b[i+1]>> 4));
** buf[2]= (byte)(((b[i+1] & 0x0F)<< 2)|(b[i+2]>> 6));
** buf[3]= (byte)(b[i+2] & 0x3F);
** send(out, BaseTable[buf[0]] + BaseTable[buf[1]] +
** BaseTable[buf[2]] + BaseTable[buf[3]]);
**/
if ((linelength += 4) >= 76)
{
send(out, "\r\n");
linelength = 0;
}
i += 3;
}
// Các ký tự thêm vào...
if (nrest == 2)
{
// 2 bytes còn lại
buf[0] = (byte)(( bytes[k] & 0xFC) >> 2);
buf[1] = (byte)(((bytes[k] & 0x03) << 4) |
((bytes[k+1] & 0xF0) >> 4));
buf[2] = (byte)(( bytes[k+1] & 0x0F) << 2);
}
else if (nrest == 1)
{
// 1 byte còn lại
buf[0] = (byte)((bytes[k] & 0xFC) >> 2);
buf[1] = (byte)((bytes[k] & 0x03) << 4);
}
if (nrest > 0)
{
// Gửi ký tự thêm vào
if ((linelength += 4) >= 76)
send(out, "\r\n");
send(out, BaseTable[buf[0]]);
send(out, BaseTable[buf[1]]);
if (nrest == 2)
{
send(out, BaseTable[buf[2]]);
}
else
{
send(out, "=");
}
send(out, "=");
}
out.flush();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void send(BufferedWriter out, String s)
{
try
{
out.write(s);
System.out.print(s);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Nếu muốn gửi file gif và file text, bạn phải thay đổi hàm sendMail() lại một chút.
...
/* Tên của các file được gửi. */
String FileName1 = "gumby.gif";
String FileName2 = "gumby.txt";
...
public void sendMail(String mailServer, String recipient)
{
System.out.println("Send mail with attached file");
try
{
Socket s = new Socket(mailServer, 25);
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream(), "8859_1"));
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(s.getOutputStream(),"8859_1"));
String boundary = "DataSeparatorString";
// Giả sử lúc này bạn đã gửi username
sendln(in, out, "HELO world");
sendln(in, out, "MAIL FROM: <real@gagnon.com>");
sendln(in, out, "RCPT TO: <" + recipient + ">" );
sendln(in, out, "DATA");
sendln(out, "MIME-Version: 1.0");
sendln(out, "Subject: remember me");
sendln(out,
"From: Elvis Presley <Elvis.Presley@jailhouse.rock<");
sendln(out,
"Content-Type: multipart/mixed; boundary=\"" +
boundary + "\"");
sendln(out, "\r\n--" + boundary);
// Gửi file GIF
sendln(out,
"Content-Type: text/plain; charset=\"us-ascii\"\r\n");
sendln(out, "I'm alive. Help me!\n\n");
sendln(out, "\r\n" + "--" + boundary );
sendln(out, "Content-Type:image/gif; name=" + FileName1);
sendln(out, "Content-Disposition: attachment;filename=\"" +
FileName1 + "\"");
sendln(out, "Content-transfer-encoding: base64\r\n");
MIMEBase64.encode(FileName1, out);
sendln(out, "\r\n--" + boundary);
// File text
sendln(out, "Content-Type: text/plain; name=" + FileName2);
sendln(out, "Content-Disposition: inline;filename=\"" + FileName2 + "\"");
// Để gửi kèm file thay vì gửi trong mail:
// sendln(out, "Content-Type: text/plain; name=" +
// FileName2);
// sendln(out,
// "Content-Disposition: attachment;filename=\""+
// FileName2+"\"");
sendln(out, "Content-Transfer-Encoding: base64\r\n");
MIMEBase64.encode(FileName2, out);
sendln(out, "\r\n\r\n--" + boundary + "--\r\n");
// ok
sendln(in, out,".");
sendln(in, out, "QUIT");
s.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
...
Trích từ “Thủ thuật lập trình Java“