java实现一个发邮件功能(文本和附件,以163邮箱为例)
- 首先,注册一个163邮箱,之后设置中开启POP3/SMTP/IMAP,开启后会生成一个授权码。保存下来。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/c0f26f03804871f4e439d1cfbc3f6b67.png)
- 建一个maven项目,导入jar包
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
- 编写发邮件代码工具类
public class emailUtils {
private static final String USEREMAAL = "邮箱地址";
private static final String PASSWORD = "授权码";
public static boolean sendMail(String to,String cc, String text, String title,String filePath){
try {
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.user", USEREMAAL);
props.put("mail.password", PASSWORD);
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
Session mailSession = Session.getInstance(props, authenticator);
MimeMessage message = new MimeMessage(mailSession);
String username = props.getProperty("mail.user");
InternetAddress form = new InternetAddress(username);
message.setFrom(form);
InternetAddress toAddress = new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO, toAddress);
if (cc!=null) {
InternetAddress ccAddress = new InternetAddress(cc);
message.setRecipient(Message.RecipientType.CC, ccAddress);
}
message.setSubject(title);
message.setContent(text, "text/html;charset=UTF-8");
MimeBodyPart mimeBodyPart = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new FileDataSource(filePath));
mimeBodyPart.setDataHandler(dataHandler);
mimeBodyPart.setFileName(MimeUtility.encodeText("附件"));
MimeBodyPart text1 = new MimeBodyPart();
text1.setContent(text,"text/html;charset=UTF-8");
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(mimeBodyPart);
mimeMultipart.addBodyPart(text1);
mimeMultipart.setSubType("mixed");
message.setContent(mimeMultipart);
message.setSentDate(new Date());
Transport.send(message);
return true;
}catch (SMTPAddressFailedException ex) {
ex.getReturnCode();
ex.getMessage();
System.out.println("SMTPAddressFailedException---------------------------"+ ex.getReturnCode());
System.out.println("SMTPAddressFailedException---------------------------"+ ex.getCause().getMessage());
} catch (MessagingException mex) {
mex.getMessage();
System.out.println("MessagingException------" + mex.getMessage());
}catch (Exception e){
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws Exception {
sendMail("要给邮箱发送地址",“抄送人”,"文本","邮件标题","附件路径");
System.out.println("===发送成功====");
}