下面列出了javax.mail.Transport#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void notify(String subject, String message) {
if (this.from != null && !this.to.isEmpty()) {
Message msg = new MimeMessage(this.session);
try {
Address[] recipients = this.to.toArray(new Address[this.to.size()]);
Transport transport = this.session.getTransport();
msg.setFrom(this.from);
msg.addRecipients(Message.RecipientType.TO, recipients);
msg.setSubject(subject);
msg.setText(message);
transport.connect();
transport.sendMessage(msg, recipients);
transport.close();
} catch (MessagingException e) {
logger.error("Error while sending notification message '" + subject + "'", e);
}
} else {
logger.warn("From is null or to is empty. Notification won't be send.");
}
}
/**
*
* @param fr 发送人姓名 fr 发送人姓名
* @param to 收件人地址 to 收件人地址
* @param title 邮件主题 title 邮件主题
* @param content 邮件内容 content 邮件内容
* @return return
*/
public boolean send(String fr, String to, String title, String content) {
log.warn("[send email][fr:{}][to:{}][title:{}][content:{}]", fr,to,title,content);
try {
Session mailSession = Session.getDefaultInstance(props);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(config.ACCOUNT,fr));
msg.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
msg.setSubject(title + "");
msg.setContent(content + "", "text/html;charset=UTF-8");
msg.saveChanges();
Transport transport = mailSession.getTransport("smtp");
transport.connect(config.HOST,
config.ACCOUNT,
config.PASSWORD);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
private void putOnTransport(Session session, Message msg) throws SenderException {
// connect to the transport
Transport transport = null;
try {
transport = session.getTransport("smtp");
transport.connect(getSmtpHost(), getCredentialFactory().getUsername(), getCredentialFactory().getPassword());
if (log.isDebugEnabled()) {
log.debug("MailSender [" + getName() + "] connected transport to URL [" + transport.getURLName() + "]");
}
transport.sendMessage(msg, msg.getAllRecipients());
} catch (Exception e) {
throw new SenderException("MailSender [" + getName() + "] cannot connect send message to smtpHost [" + getSmtpHost() + "]", e);
} finally {
if (transport != null) {
try {
transport.close();
} catch (MessagingException e1) {
log.warn("MailSender [" + getName() + "] got exception closing connection", e1);
}
}
}
}
public void init()
{
if (_toList.size() == 0)
throw new ConfigException(L.l("mail service requires at least one 'to' address"));
_to = new Address[_toList.size()];
_toList.toArray(_to);
_from = new Address[_fromList.size()];
_fromList.toArray(_from);
try {
if (_session == null) {
_session = Session.getInstance(_properties);
}
Transport smtp = _session.getTransport("smtp");
smtp.close();
} catch (Exception e) {
throw ConfigException.wrap(e);
}
}
@Test
public void testSendTwoMessagesSameConnection() throws MessagingException {
MimeMessage[] mimeMessages = new MimeMessage[2];
Properties mailProps = getMailProperties(server.getPort());
Session session = Session.getInstance(mailProps, null);
mimeMessages[0] = createMessage(session, "[email protected]", "[email protected]", "Doodle1", "Bug1");
mimeMessages[1] = createMessage(session, "[email protected]", "[email protected]", "Doodle2", "Bug2");
Transport transport = session.getTransport("smtp");
transport.connect("localhost", server.getPort(), null, null);
for (int i = 0; i < mimeMessages.length; i++) {
MimeMessage mimeMessage = mimeMessages[i];
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
transport.close();
assertThat(server.getReceivedEmails(), hasSize(2));
}
/**
* �����ʼ�
*/
private void sendEmail(String host,String account,String pwd){
//��������
try {
this.message.setSentDate(new Date());
this.message.setContent(this.multipart);
this.message.saveChanges();
Transport transport=session.getTransport("smtp");
transport.connect(host,account,pwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
} catch (MessagingException e) {
errorMessage = "�����ʼ�ʧ��(�����ռ��������ַ�����糬ʱ):"+e.getMessage();
e.printStackTrace();
}
}
private void sendOut() throws MessagingException {
mimeMessage.setContent(multipart);
mimeMessage.saveChanges();
Session mailSession = Session.getInstance(props, null);
Transport transport = mailSession.getTransport("smtp");
transport.connect((String) props.get("mail.smtp.host"), username,
password);
transport.sendMessage(mimeMessage,
mimeMessage.getRecipients(Message.RecipientType.TO));
transport.close();
}
/** */
public void testSendTwoMessagesSameConnection()
throws IOException
{
try
{
MimeMessage[] mimeMessages = new MimeMessage[2];
Properties mailProps = this.getMailProperties(SMTP_PORT);
Session session = Session.getInstance(mailProps, null);
// session.setDebug(true);
mimeMessages[0] = this.createMessage(session, "[email protected]", "[email protected]", "Doodle1", "Bug1");
mimeMessages[1] = this.createMessage(session, "[email protected]", "[email protected]", "Doodle2", "Bug2");
Transport transport = session.getTransport("smtp");
transport.connect("localhost", SMTP_PORT, null, null);
for (MimeMessage mimeMessage : mimeMessages)
{
transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
}
transport.close();
}
catch (MessagingException e)
{
e.printStackTrace();
fail("Unexpected exception: " + e);
}
assertEquals(2, this.server.getMessages().size());
}
/**
* send email
*
* @throws MessagingException
* @throws Exception
*/
public static int sendMail(String subject, String content, String mails,
String cc) throws MessagingException {
Properties props = new Properties();
props.put("mail.smtp.host", HOST);
props.put("mail.smtp.starttls.enable", "true");
// props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
// props.put("mail.debug", "true");
Session mailSession = Session.getInstance(props, new MyAuthenticator());
Message message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(FROM));
message.addRecipients(Message.RecipientType.TO, getMailList(mails));
message.addRecipients(Message.RecipientType.CC, getMailList(cc));
message.setSubject(subject);
message.setContent(content, "text/html;charset=utf-8");
Transport transport = mailSession.getTransport("smtp");
try {
transport.connect(HOST, USER, PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
} finally {
if (transport != null)
transport.close();
}
return 0;
}
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
prop.setProperty("mail.debug", "true");
prop.setProperty("mail.host", MAIL_SERVER_HOST);
prop.setProperty("mail.transport.protocol", "smtp");
prop.setProperty("mail.smtp.auth", "true");
// 1、创建session
Session session = Session.getInstance(prop);
Transport ts = null;
// 2、通过session得到transport对象
ts = session.getTransport();
// 3、连上邮件服务器
ts.connect(MAIL_SERVER_HOST, USER, PASSWORD);
// 4、创建邮件
MimeMessage message = new MimeMessage(session);
// 邮件消息头
message.setFrom(new InternetAddress(MAIL_FROM)); // 邮件的发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // 邮件的收件人
message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // 邮件的抄送人
message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // 邮件的密送人
message.setSubject("测试文本邮件"); // 邮件的标题
// 邮件消息体
message.setText("天下无双。");
// 5、发送邮件
ts.sendMessage(message, message.getAllRecipients());
ts.close();
}
/**
* Validate that this instance can connect to the server that it is configured
* for. Throws a {@link MessagingException} if the connection attempt failed.
*/
public void testConnection() throws MessagingException {
Transport transport = null;
try {
transport = connectTransport();
}
finally {
if (transport != null) {
transport.close();
}
}
}
private boolean sendMail(boolean isResolve, ClusterAlertBean clusterAlertBean) {
try {
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", properties.getProperty(MAIL_SERVER));
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(props);
Message msg = new MimeMessage(session);
msg.setSubject("DBLE告警 " + (isResolve ? "RESOLVE\n" : "ALERT\n"));
StringBuilder builder = new StringBuilder();
builder.append(groupMailMsg(clusterAlertBean, isResolve));
msg.setText(builder.toString());
msg.setFrom(new InternetAddress(properties.getProperty(MAIL_SENDER)));
Transport transport = session.getTransport();
transport.connect(properties.getProperty(MAIL_SERVER), properties.getProperty(MAIL_SENDER), properties.getProperty(SENDER_PASSWORD));
transport.sendMessage(msg, new Address[]{new InternetAddress(properties.getProperty(MAIL_RECEIVE))});
transport.close();
//send EMAIL SUCCESS return TRUE
return true;
} catch (Exception e) {
e.printStackTrace();
}
//send fail reutrn false
return false;
}
/**
* Validate that this instance can connect to the server that it is configured
* for. Throws a {@link MessagingException} if the connection attempt failed.
*/
public void testConnection() throws MessagingException {
Transport transport = null;
try {
transport = connectTransport();
}
finally {
if (transport != null) {
transport.close();
}
}
}
private void sendAuthenticated(EmailProperties emailProperties, Message message, Session session) throws MessagingException {
String host = emailProperties.getJavamailOption(EmailPropertyKeys.JAVAMAIL_HOST_KEY);
int port = NumberUtils.toInt(emailProperties.getJavamailOption(EmailPropertyKeys.JAVAMAIL_PORT_KEY));
String username = emailProperties.getJavamailOption(EmailPropertyKeys.JAVAMAIL_USER_KEY);
String password = emailProperties.getJavamailOption(EmailPropertyKeys.JAVAMAIL_PASSWORD_KEY);
Transport transport = session.getTransport("smtp");
try {
transport.connect(host, port, username, password);
transport.sendMessage(message, message.getAllRecipients());
} finally {
transport.close();
}
}
public boolean send() throws Exception {
Properties props = _setProperties();
if (!_user.equals("") && !_pass.equals("") && _to.length > 0 && !_from.equals("") &&
!_subject.equals("") && !_body.equals("")) {
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(ApplicationConstants.USERNAME_FOR_SMTP, ApplicationConstants.PASSWORD_FOR_SMTP);
}
});
SMTPAuthenticator authentication = new SMTPAuthenticator();
javax.mail.Message msg = new MimeMessage(Session
.getDefaultInstance(props, authentication));
msg.setFrom(new InternetAddress(_from));
InternetAddress[] addressTo = new InternetAddress[_to.length];
for (int i = 0; i < _to.length; i++) {
addressTo[i] = new InternetAddress(_to[i]);
}
msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
msg.setSubject(_subject);
msg.setSentDate(new Date());
// setup message body
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(_body);
_multipart.addBodyPart(messageBodyPart);
// Put parts in message
msg.setContent(_multipart);
// send email
String protocol = "smtp";
props.put("mail." + protocol + ".auth", "true");
Transport t = session.getTransport(protocol);
try {
t.connect(ApplicationConstants.HOST_FOR_MAIL, ApplicationConstants.USERNAME_FOR_SMTP, ApplicationConstants.PASSWORD_FOR_SMTP);
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}
return true;
} else {
return false;
}
}
private static Boolean sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
return true;
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
return false;
}
public static void main(String[] args) throws Exception {
// Create a Properties object to contain connection configuration information.
Properties props = System.getProperties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
// Create a Session object to represent a mail session with the specified properties.
Session session = Session.getDefaultInstance(props);
// Create a message with the specified information.
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(senderAddress,senderName));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toAddresses));
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccAddresses));
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bccAddresses));
msg.setSubject(subject);
msg.setContent(htmlBody,"text/html");
// Add headers for configuration set and message tags to the message.
msg.setHeader("X-SES-CONFIGURATION-SET", configurationSet);
msg.setHeader("X-SES-MESSAGE-TAGS", tag0);
msg.setHeader("X-SES-MESSAGE-TAGS", tag1);
// Create a transport.
Transport transport = session.getTransport();
// Send the message.
try {
System.out.println("Sending...");
// Connect to Amazon Pinpoint using the SMTP username and password you specified above.
transport.connect(smtpEndpoint, smtpUsername, smtpPassword);
// Send the email.
transport.sendMessage(msg, msg.getAllRecipients());
System.out.println("Email sent!");
}
catch (Exception ex) {
System.out.println("The email wasn't sent. Error message: "
+ ex.getMessage());
}
finally {
// Close the connection to the SMTP server.
transport.close();
}
}
public static void main(String args[]) throws Exception {
// read test configuration from test.properties in your classpath
Properties testProps = TestUtil.readProperties();
// get a JavaMail Session object
Session session = Session.getDefaultInstance(testProps, null);
///////// beginning of DKIM FOR JAVAMAIL stuff
// get DKIMSigner object
DKIMSigner dkimSigner = new DKIMSigner(
testProps.getProperty("mail.smtp.dkim.signingdomain"),
testProps.getProperty("mail.smtp.dkim.selector"),
testProps.getProperty("mail.smtp.dkim.privatekey"));
/* set an address or user-id of the user on behalf this message was signed;
* this identity is up to you, except the domain part must be the signing domain
* or a subdomain of the signing domain.
*/
dkimSigner.setIdentity("[email protected]"+testProps.getProperty("mail.smtp.dkim.signingdomain"));
// get default
System.out.println("Default headers getting signed if available:");
TestUtil.printArray(dkimSigner.getDefaultHeadersToSign());
// the following header will be signed as well if available
dkimSigner.addHeaderToSign("ASpecialHeader");
// the following header won't be signed
dkimSigner.removeHeaderToSign("Content-Type");
// change default canonicalizations
dkimSigner.setHeaderCanonicalization(Canonicalization.SIMPLE);
dkimSigner.setBodyCanonicalization(Canonicalization.RELAXED);
// add length param to the signature, see RFC 4871
dkimSigner.setLengthParam(true);
// change default signing algorithm
dkimSigner.setSigningAlgorithm(SigningAlgorithm.SHA1withRSA);
// add a list of header=value pairs to the signature for debugging reasons
dkimSigner.setZParam(true);
///////// end of DKIM FOR JAVAMAIL stuff
// construct the JavaMail message using the DKIM message type from DKIM for JavaMail
Message msg = new SMTPDKIMMessage(session, dkimSigner);
Multipart mp = new MimeMultipart();
msg.setFrom(new InternetAddress(testProps.getProperty("mail.smtp.from")));
if (testProps.getProperty("mail.smtp.to") != null) {
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(testProps.getProperty("mail.smtp.to"), false));
}
if (testProps.getProperty("mail.smtp.cc") != null) {
msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(testProps.getProperty("mail.smtp.cc"), false));
}
msg.setSubject("DKIM for JavaMail: FullExample Testmessage");
MimeBodyPart mbp_msgtext = new MimeBodyPart();
mbp_msgtext.setText(TestUtil.bodyText);
mp.addBodyPart(mbp_msgtext);
TestUtil.addFileAttachment(mp, testProps.get("mail.smtp.attachment"));
msg.setContent(mp);
// send the message by JavaMail
Transport transport = session.getTransport("smtp"); // or smtps ( = TLS)
transport.connect(testProps.getProperty("mail.smtp.host"),
testProps.getProperty("mail.smtp.auth.user"),
testProps.getProperty("mail.smtp.auth.password"));
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
/**
* Sends an email to a given recipient for a given subject and content
* with a {@code reply-to} header.
*
* @param to The recipient of the mail ({@code to} header).
* @param subject The subject of the mail.
* @param text The content of the mail.
* @param replyTo The {@code reply-to} email header.
* @return {@code true} if successful, {@code false} otherwise.
*/
private static boolean sendEmail(String to, String subject, String text, String replyTo) {
final boolean emailEnabled = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAILS_ENABLED).getBoolValue();
if (!emailEnabled) {
logger.error("Tried to send a mail, but sending emails is disabled. Update your system settings.");
return false;
}
final String smtpHost = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_SMTP_HOST).getStringValue();
final int smtpPort = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_SMTP_PORT).getIntValue();
final String emailAddress = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_ADDRESS).getStringValue();
final String emailPassword = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.EMAIL_PASSWORD).getStringValue();
final boolean debug = AdminDAO.getSystemSetting(AdminSystemSettings.SETTING_NAME.DEBUG_MODE).getBoolValue();
try {
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailAddress, emailPassword);
}});
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(emailAddress));
msg.setReplyTo(InternetAddress.parse(replyTo));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
msg.setSubject(subject);
msg.setContent(text, "text/plain");
msg.setSentDate(new Date());
Transport transport = session.getTransport("smtp");
transport.connect(smtpHost, smtpPort, emailAddress, emailPassword);
Transport.send(msg);
transport.close();
logger.info(String.format("Mail sent: to: %s, replyTo: %s", to, replyTo));
} catch (MessagingException messagingException) {
logger.warn("Failed to send email.", messagingException);
return false;
}
return true;
}
public boolean sendLog(String host, String userId, String password,
String to, String from, String subject, String message,
File filename) {
boolean success = true;
System.out.println("host: " + host);
System.out.println("userId: " + userId);
// Fortify Mod: commented out clear text password.
// System.out.println("password: " + password);
System.out.println("to: " + to);
System.out.println("from: " + from);
System.out.println("subject: " + subject);
System.out.println("message: " + message);
System.out.println("filename: " + filename.getName());
System.out.println("filename: " + filename.getAbsolutePath());
// create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props, null);
session.setDebug(true);
try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = { new InternetAddress(to) };
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(message);
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
FileDataSource fds = new FileDataSource(filename);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
// set the Date: header
msg.setSentDate(new Date());
// connect to the transport
Transport trans = session.getTransport("smtp");
trans.connect(host, userId, password);
// send the message
trans.sendMessage(msg, msg.getAllRecipients());
// smtphost
trans.close();
} catch (MessagingException mex) {
success = false;
mex.printStackTrace();
Exception ex = null;
if ((ex = mex.getNextException()) != null) {
ex.printStackTrace();
}
}
return success;
}