发邮件

发送邮件需要知道的
邮件服务器地址
邮件服务器端口

是否需要验证(用户名、密码)
发件人地址
用户名
密码

收件人地址
邮件主题
邮件内容
附件

发送协议: SMTP 端口号25
收取协议: POP3 端口号110 IMAP协议

发送邮件的服务
sendcloud,当一次发多封邮件的时候将邮件放在队列中。

发送邮件的组件
commons-email:
mail.jar
在使用的时候删除掉系统自带的mail文件夹

发送文本邮件
/
简单文本邮件的发送
@param subject 邮件主题
@param msg 文本邮件的内容
@param email 收件人Email地址
/
public static void sendSimpleEmail(String subject,String msg,String email) {
try {
/
创建出简单文本邮件对象
/
SimpleEmail simpleEmail = new SimpleEmail();
/
设置邮件发送的服务器主机名、用户名和密码、字符集、设置为发送
/
simpleEmail.setHostName("smtp.qq.com");
simpleEmail.setAuthentication("1120879294", "shenlan@18446744@");
simpleEmail.setCharset("UTF-8");
simpleEmail.setTLS(true);
/
设定发件人的地址、邮件主题、内容、发件人地址
/
simpleEmail.setFrom("1120879294@qq.com");
simpleEmail.setSubject(subject);
simpleEmail.setMsg(msg);
simpleEmail.addTo(email);
/
发送邮件
/
simpleEmail.send();
} catch (EmailException e) {
e.printStackTrace();
}
}
发送HTML邮件
/
HTML邮件的发送
@param subject 邮件主题
@param msg 邮件内容
@param email 收件人的Email地址
/
public static void sendHtmlEmail(String subject, String msg, String email) {
try {
/
创建出一个可以发送HTML的邮件对象
/
HtmlEmail htmlEmail = new HtmlEmail();
/
设置邮件发送的服务器主机名、用户名和密码、字符集、设置为发送
/
htmlEmail.setHostName("smtp.qq.com");
htmlEmail.setAuthentication("1120879294", "shenlan@18446744@");
htmlEmail.setCharset("UTF-8");
htmlEmail.setTLS(true);
/
设置邮件发送的服务器主机名、用户名和密码、字符集、设置为发送
/
htmlEmail.setFrom("1120879294@qq.com");
htmlEmail.setSubject(subject);
htmlEmail.setHtmlMsg(msg);
htmlEmail.addTo(email);
/
发送邮件
/
htmlEmail.send();
} catch (EmailException e) {
e.printStackTrace();
}
}

发送带有附件的邮件
/
带有附件的邮件发送
@param subject 邮件主题
@param msg 邮件内容
@param email 收件人Email地址
@param path 附件的路径
/
public static void sendAttachmentEmail(String subject, String msg, String email,String path) {
try {
/
新建附件
/
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(path);
/
创建一个可以发送附件的邮件对象
/
MultiPartEmail attachmentEmail = new MultiPartEmail();
/
设置邮件发送的服务器主机名、用户名和密码、字符集、设置为发送
/
attachmentEmail.setHostName("smtp.qq.com");
attachmentEmail.setAuthentication("1120879294", "shenlan@18446744@");
attachmentEmail.setCharset("UTF-8");
attachmentEmail.setTLS(true);
/
设置邮件发送的服务器主机名、用户名和密码、字符集、设置为发送
/
attachmentEmail.setFrom("1120879294@qq.com");
attachmentEmail.setSubject(subject);
attachmentEmail.setMsg(msg);
attachmentEmail.addTo(email);
/
在发送带有附件的邮件之前先把附件添加到邮件中
/
attachmentEmail.attach(attachment);
/
发送邮件
/
attachmentEmail.send();
} catch (EmailException e) {
e.printStackTrace();
}
}
}

应用:
借书还书的时候通知用户
在发送邮件的时候要将邮件发送的程序写成一个单独的子线程来发送

Email HTML template
发送HTML邮件的模板


原文地址:https://www.cnblogs.com/shininguang/p/4923409.html