public class EmailUtil {
private static String from = "";//发送者的谷歌邮箱
private static String password = "";//谷歌邮箱密码
public static boolean sendMailGMail(String to, String content) {
return gmailSender(from,password,to,"标题", content);
}
public static void sendFile(String to,String url){
System.out.println(to);
System.out.println(url);
// 发件人和收件人的电子邮件地址
String senderEmail = from;
String recipientEmail = to;
// 发件人的邮箱凭据
String senderUsername = from;
String senderPassword = password;
// 邮件主题和内容
String subject = "附件示例";
String body = "这是一个带有附件的电子邮件示例";
// 附件文件路径
String filePath = url;
Properties props = new Properties();
gmailSsl(props);
// 创建会话对象
Session session = Session.getInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderUsername, senderPassword);
}
});
try {
// 创建MimeMessage对象
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderEmail));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientEmail));
message.setSubject(subject);
// 创建多部分消息
MimeMultipart multipart = new MimeMultipart();
// 创建文本部分
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(body);
// 创建文件部分
MimeBodyPart filePart = new MimeBodyPart();
URLDataSource source = new URLDataSource(new URL(filePath));
filePart.setDataHandler(new DataHandler(source));
filePart.setFileName(source.getName());
// 添加部分到多部分消息
multipart.addBodyPart(textPart);
multipart.addBodyPart(filePart);
// 将多部分消息设置为消息内容
message.setContent(multipart);
// 发送邮件
Transport.send(message);
System.out.println("电子邮件已发送成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void gmailSsl(Properties props) {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
props.put("mail.debug", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.port", "465");
//props.put("mail.smtp.port", "587");
props.put("mail.smtp.socketFactory.port", "465");
//props.put("mail.smtp.socketFactory.port", "587");
props.put("mail.smtp.auth", "true");
}
public static boolean gmailSender(String from,String password,String email,String subject,String content) {
Properties props = new Properties();
gmailSsl(props);
Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password);
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(from));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(email));
msg.setSubject(subject);
msg.setText(content);
msg.setSentDate(new Date());
Transport.send(msg);
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
return true;
}
}
谷歌邮箱发送文件、信息
最新推荐文章于 2024-07-12 16:03:26 发布