public class Mail {
private String mailServer,from,to,mailSubject,mailContent;
private String username,password;
public Mail(){
//设置邮件信息
//进行认证登录的用户名
username="hq@mail.com";
//认证密码
password="hq";
//认证的邮箱对应的邮件服务器
mailServer="192.168.17.176";
//发件人信息
from="wj";
//收件人信息
to="wj@mail.com";
//邮件标题
mailSubject="我们都是好孩子333";
//邮件内容
mailContent="这是一封测试邮件!如有雷同,纯属不可能";
}
//设置邮件服务器
@SuppressWarnings("static-access")
public void send(){
Properties prop=System.getProperties();
//指定邮件server
prop.put("mail.smtp.host", mailServer);
//是否开启认证
prop.put("mail.smtp.auth", "true");
//smtp协议的
prop.put("mail.smtp.port", "25");
//产生Session服务
EmailAuthenticator mailauth=new EmailAuthenticator(username, password);
Session mailSession=Session.getInstance(prop,(Authenticator)mailauth);
try {
//封装Message对象
Message message=new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from)); //发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));//收件人
message.setSubject(mailSubject);
//设置内容(设置字符集处理乱码问题)
message.setContent(mailContent,"text/html;charset=gbk");
message.setSentDate(new Date());
//创建Transport实例,发送邮件
Transport tran=mailSession.getTransport("smtp");
tran.send(message,message.getAllRecipients());
tran.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public class MyTest {
public static void main(String[] args) {
Mail mail=new Mail();
mail.send();
System.out.println("success!");
}
}
public class MailWithAttachment {
private JavaMailSender mailSender; //必须使用 JavaMailSender
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void send() throws MessagingException,IOException{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom("hq@mail.com");
helper.setTo("wj@mail.com");
helper.setSubject("哈哈哈");
helper.setText("每日一笑,开开心心!!!");
//添加附件1
ClassPathResource file1 = new ClassPathResource(
"/cn/bdqn/attachfiles/test.doc");
helper.addAttachment(file1.getFilename(), file1.getFile());
//添加附件2:附件的文件名为中文时,需要对文件名进行编码转换,解决乱码问题
ClassPathResource file2 = new ClassPathResource(
"/cn/bdqn/attachfiles/附件测试文件.doc");
helper.addAttachment(MimeUtility.encodeWord(file2.getFilename()),file2.getFile());
mailSender.send(mimeMessage);
}
}
public class MailTest {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
/*测试带附件的邮件*/
try{
MailWithAttachment mailWithAttach = (MailWithAttachment)context.getBean("mailWithAttachment");
mailWithAttach.send();
}catch(Exception e){
System.out.print(e.toString());
}
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有