📄 mail.java
字号:
import java.util.* ;
import java.io.* ;
import javax.mail.* ;
import javax.mail.internet.* ;
import javax.activation.* ;
public class Mail {
String[] to;
String[] cc;
String[] bcc;
String from;
String host="";
String subject="";
String body="";
Vector files = new Vector();
public Mail (String[] to,String from,String smtpServer,String subject,String body){
this.to=to;
this.from=from;
this.host=smtpServer;
this.subject=subject;
this.body = body;
}
public void setCc(String[] cc){//抄送
this.cc = cc;
}
public void setBcc(String[] bcc){//暗送
this.bcc = bcc;
}
public void attachfile(String fname){
files.addElement(fname);
}
public boolean send(){
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
Session session=Session.getDefaultInstance(props, null);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
//设置收件人
InternetAddress[] address= new InternetAddress[to.length];
for(int i=0;i<to.length;i++){
address[i] = new InternetAddress(to[i]);
}
msg.setRecipients(Message.RecipientType.TO,address);
//设置抄送人
if(cc != null){
address= new InternetAddress[cc.length];
for(int i=0;i<cc.length;i++){
address[i] = new InternetAddress(cc[i]);
}
msg.setRecipients(Message.RecipientType.CC,address);
}
//设置暗送人
if(bcc != null){
address= new InternetAddress[bcc.length];
for(int i=0;i<bcc.length;i++){
address[i] = new InternetAddress(bcc[i]);
}
msg.setRecipients(Message.RecipientType.BCC,address);
}
//设置邮件主题
msg.setSubject(subject);
//创建复合邮件体,后面的BodyPart将加入到此处创建的Multipart中
Multipart mp = new MimeMultipart();
MimeBodyPart mbp = null;
mbp = new MimeBodyPart();
mbp.setText(body);
mp.addBodyPart(mbp);
for(int i=0;i<files.size();i++){
String fileName = (String)files.elementAt(i);
mbp=new MimeBodyPart();
FileDataSource fds=new FileDataSource(fileName);
mbp.setDataHandler(new DataHandler(fds));
mbp.setFileName(fds.getName());
mp.addBodyPart(mbp);
}
files.removeAllElements();
msg.setContent(mp);
msg.setSentDate(new Date());
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
return false;
}
return true;
}
public static void main(String[] args){
String[] to = {"xdf1@xdf.com"};
String[] cc = {"xdf2@xdf.com","xdf3@xdf.com"};
String[] bcc = {"xdf4@xdf.com"};
String body = "最后一次想你!\nbye-bye,world!";
Mail mail = new Mail(to,"scott@zhangsan.com","127.0.0.1","测试带附件的邮件",body);
mail.setCc(cc);
mail.setBcc(bcc);
mail.attachfile("E:\\ex\\love.pps");
mail.send();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -