JavaMail实现发送邮件,可添加附件(JAVA SWING)

时间:2022-12-22 12:33:45

到这里来下载这个软件吧   http://home.ustc.edu.cn/~cwtree/


共有4个文件,其中Authenticator是完成你的邮箱的用户名密码验证的,但是这个验证要看你用的是哪一个邮件服务器,有的服务器需要验证,有的服务器不需要验证

你也可以不需要这个功能,设置mail.smtp.auth 为false就行了

代码展示
Mail.java
-------------------------
package cn.edu.ustc.mail;

import java.util.Properties;

public class Mail {

private String fromAddress;
private String toAddress;
private String subject;
private String content;
private String attach;
private String mailHost;
private String username;
private String password;
private boolean validate;

public String getFromAddress() {
return fromAddress;
}

public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}

public String getToAddress() {
return toAddress;
}

public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}

public String getSubject() {
return subject;
}

public void setSubject(String subject) {
this.subject = subject;
}

public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getAttach() {
return attach;
}

public void setAttach(String attach) {
this.attach = attach;
}

public String getMailHost() {
return mailHost;
}

public void setMailHost(String mailHost) {
this.mailHost = mailHost;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public boolean isValidate() {
return validate;
}

public void setValidate(boolean validate) {
this.validate = validate;
}
public Properties getProperties() {
Properties p = new Properties();
p.put("mail.smtp.host", mailHost);
p.put("mail.transport.protocol", "smtp");
p.put("mail.smtp.auth", validate?"true":"false");
return p;
}
}
---------------------------------
MailAuthenticator.java
---------------------------------
package cn.edu.ustc.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class MailAuthenticator extends Authenticator {

String username = null;
String password = null;
public MailAuthenticator(){}
public MailAuthenticator(String username,String password) {
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
---------------------------------
SendMail.java
---------------------------------
package cn.edu.ustc.mail;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
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 static boolean flag = false;
public static boolean send(Mail mail) throws Exception{
//首先判断是否需要验证
//validate为true表明需要验证,但是是否真的验证了还要根据邮件服务器,有的服务器验证,有的不需要验证
MailAuthenticator authenticator = null;
Properties prop = mail.getProperties();
if(mail.isValidate()) {
authenticator = new MailAuthenticator(mail.getUsername(),mail.getPassword());
}
//根据属性和密码验证器生成一个邮件session
Session session = Session.getDefaultInstance(prop,authenticator);
try {
Message message = new MimeMessage(session);
Address from = new InternetAddress(mail.getFromAddress());
message.setFrom(from);
Address to = new InternetAddress(mail.getToAddress());
message.setRecipient(Message.RecipientType.TO, to);
message.setSubject(mail.getSubject());
Multipart mainPart = new MimeMultipart();//邮件的主体,让它装载所有邮件内容
BodyPart body = new MimeBodyPart();//邮件主体的子部分
//邮件正文内容
body.setContent(mail.getContent(),"text/html;charset=utf-8");
BodyPart attachbody = null;
if(null==mail.getAttach()||"".equals(mail.getAttach())) {
}else {
//开始处理邮件的附件
attachbody = new MimeBodyPart();
FileDataSource fds = new FileDataSource(mail.getAttach());
DataHandler dh = new DataHandler(fds);
//提取文件名
String attach = mail.getAttach();
String fileName = attach.substring(attach.lastIndexOf("\"));
attachbody.setFileName(new String(fileName.getBytes("GB2312")));
attachbody.setDataHandler(dh);
}
mainPart.addBodyPart(body);
mainPart.addBodyPart(attachbody);
message.setContent(mainPart);
Transport.send(message);
System.out.println("邮件发送成功\\(^o^)//~");
flag = true;
} catch (Exception e) {
System.out.println("邮件发送失败╮(╯▽╰)╭");
flag = false;
throw e;
}
return flag;
}
}
---------------------------------
MainFrame.java
---------------------------------
package cn.edu.ustc.mail;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class MainFrame {

private static JFrame frame = new JFrame("快速邮件发送");
private static FlowLayout fl = new FlowLayout(FlowLayout.LEFT);
private static JPanel panel1_umail = new JPanel(new BorderLayout());

private static JPanel panel2_tmail = new JPanel(new BorderLayout());

private static JPanel panel3_subject = new JPanel(new BorderLayout());

private static JPanel panel4_content = new JPanel(new BorderLayout());

private static JPanel panel5_attach = new JPanel(new BorderLayout());

private static JPanel panel6_button = new JPanel(new GridLayout(1, 2));//装载两个按钮

private static JLabel label1_umail = new JLabel("你的邮箱:");

private static JLabel label2_tmail = new JLabel("TA的邮箱:");

private static JLabel label3_subject = new JLabel("邮件主题:");

private static JLabel label4_content = new JLabel("邮件内容:");

private static JLabel label5_attach = new JLabel("添加附件:");

private static JTextField text1_umail = new JTextField(30);

private static JTextField text2_tmail = new JTextField(30);

private static JTextField text3_subject = new JTextField(30);

private static JTextArea area_content = new JTextArea(10, 30);

private static JScrollPane scroll_content = new JScrollPane(area_content);

// 附件留空
private static JFileChooser attach = new JFileChooser();

private static JButton button_attach = new JButton("导入文件");

private static JTextField text_attach = new JTextField(30);

private static JButton button_send = new JButton("发送邮件");

private static JButton button_clear = new JButton("清空重写");

private static int width = 420;

private static int height = 350;

private static int x = (int) Toolkit.getDefaultToolkit().getScreenSize()
.getWidth()
/ 2 - width / 2;

private static int y = (int) Toolkit.getDefaultToolkit().getScreenSize()
.getHeight()
/ 2 - height / 2;

private static JOptionPane pane = new JOptionPane();

@SuppressWarnings("static-access")
private static void show() {
frame.setLayout(fl);
// 添加第一行,你的邮箱
panel1_umail.add(label1_umail, BorderLayout.WEST);
panel1_umail.add(text1_umail, BorderLayout.EAST);
frame.add(panel1_umail);
// 添加第二行,TA的邮箱
panel2_tmail.add(label2_tmail, BorderLayout.WEST);
panel2_tmail.add(text2_tmail, BorderLayout.EAST);
frame.add(panel2_tmail);
// 添加第三行,主题
panel3_subject.add(label3_subject, BorderLayout.WEST);
panel3_subject.add(text3_subject, BorderLayout.EAST);
frame.add(panel3_subject);
// 添加第四行,内容
panel4_content.add(label4_content, BorderLayout.WEST);
scroll_content.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll_content.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
area_content.setLineWrap(true);
panel4_content.add(scroll_content, BorderLayout.EAST);
frame.add(panel4_content);
// 添加第五行,附件
panel5_attach.add(label5_attach, BorderLayout.WEST);
button_attach.setPreferredSize(new Dimension(300, 20));
panel5_attach.add(button_attach, BorderLayout.EAST);
frame.add(panel5_attach);
// 添加第六行,按钮
button_send.setPreferredSize(new Dimension(200,40));
button_clear.setPreferredSize(new Dimension(200, 40));
panel6_button.add(button_send);
panel6_button.add(button_clear);
frame.add(panel6_button);
pane.showMessageDialog(null, "此程序无需您的邮箱验证,但请您使用您自己常用的邮箱发邮件!");
// 导入附件
button_attach.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
File file = null;
int state = attach.showOpenDialog(null);
file = attach.getSelectedFile();
text_attach.setText(null);
if (state == JFileChooser.APPROVE_OPTION && file != null) {
text_attach.setText(file.getAbsolutePath());
text_attach.setEditable(false);
panel5_attach.remove(button_attach);
panel5_attach.add(text_attach);
panel5_attach.setVisible(false);
panel5_attach.setVisible(true);
//attach.setVisible(false);
} else if (state == JFileChooser.CANCEL_OPTION) {
text_attach.setText(null);
}
}
});

// 清空按钮事件
button_clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
text1_umail.setText(null);
text2_tmail.setText(null);
text3_subject.setText(null);
area_content.setText(null);
text_attach.setText(null);
panel5_attach.remove(text_attach);
panel5_attach.add(button_attach);
panel5_attach.setVisible(false);
panel5_attach.setVisible(true);
}
});
// 发送邮件
button_send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Mail mail = new Mail();
String umail = text1_umail.getText();
String tmail = text2_tmail.getText();
String subject = text3_subject.getText();
String content = area_content.getText();
String attach = text_attach.getText();
mail.setFromAddress(umail);
mail.setToAddress(tmail);
mail.setSubject(subject);
mail.setContent(content);

mail.setMailHost("这里设置成你将使用的邮件服务器");
mail.setValidate(false);
mail.setAttach(attach);

try {
SendMail.send(mail);
pane.showMessageDialog(null, "发送成功O(∩_∩)O!");
text1_umail.setText(null);
text2_tmail.setText(null);
text3_subject.setText(null);
area_content.setText(null);
text_attach.setText(null);
panel5_attach.remove(text_attach);
panel5_attach.add(button_attach);
panel5_attach.setVisible(false);
panel5_attach.setVisible(true);
} catch (Exception e1) {
pane.showMessageDialog(null, "发送失败╮(╯▽╰)╭!\n"+e1.getMessage());
e1.printStackTrace();
}
}
});
frame.setVisible(true);
frame.setLocation(x, y);
frame.setSize(width, height);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
// TODO Auto-generated method stub
show();
}

}
---------------------------------

至此所有代码已经完成了,运行MainFrame.java即可。

Good Luck !