Java教程

使用java实现基本的文本内容邮件发送和附件发送

本文主要是介绍使用java实现基本的文本内容邮件发送和附件发送,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

一、java开发邮件发送文本内容
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>

 

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailUtils {
private static String from = "XXXXXXXXXX@163.com";// 用于给用户发送邮件的邮箱
private static String password = "*******"; // 邮箱的密码
private static String host = "smtp.163.com";// 发送邮件的服务器地址
public static void sendMail(String to, String title, String content) {
try {
Properties prop = new Properties();
prop.setProperty("mail.host", host);
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(prop);
session.setDebug(true);
Transport ts = session.getTransport();
ts.connect(host, from, password);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(
to));
message.setSubject(title);
message.setContent(content, "text/html;charset=UTF-8");
message.saveChanges();
ts.sendMessage(message, message.getAllRecipients());
ts.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

public static void main(String[] args) {
// 参数为接收邮件的邮箱地址和邮件主题和内容
String nowDate = new Date().toString();
sendMail("XXXXXXXXX@163.com", "java实现邮件开发", "利用改方法可以实现邮件发送!!" + nowDate);
}
}

 


二、java开发带有附件的邮件发送
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>

 

public class MailUtils {
private static String from = "XXXXXXXXXX@163.com";// 用于给用户发送邮件的邮箱
private static String password = "*******"; // 邮箱的密码
private static String host = "smtp.163.com";// 发送邮件的服务器地址
private static int port = 25;
public static void sendAttachmentMail(String to, String title, String content, String path) throws Exception {
try {
MultiPartEmail mail = new MultiPartEmail();
// 设置端口
mail.setSmtpPort(port);
// 设置邮件服务器地址
mail.setHostName(host);
// 设置密码验证
mail.setAuthentication(from, password);
// 邮件发送者
mail.setFrom(from);
// 邮件接收者
mail.addTo(to);
// 邮件编码
mail.setCharset("UTF-8");
// 邮件主题
mail.setSubject(title);
//邮件内容
mail.setMsg(content);
// 创建附件
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(path);
attachment.setDisposition(EmailAttachment.ATTACHMENT);
mail.attach(attachment);
// 设置邮件发送时间
mail.setSentDate(new Date());
// 发送邮件
mail.send();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

public static void main(String[] args) throws Exception {
sendAttachmentMail("XXXXXXXXXX@163.com", "带有附件的邮件", "这是一封带有附件的邮件!!","test.jpg");
}
}

 

这篇关于使用java实现基本的文本内容邮件发送和附件发送的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!