отправка почты из веб-приложения Java

99
8

Я работаю над веб-приложением, которое может отправлять электронную почту. Я использую javax mail api. Я смог отправить электронное письмо из тестового примера с именем Subject, отправителем, контентом. Но когда приложение запускается, оно отправляет сообщение без темы, а контент выглядит так.

------=_Part_3_47905596.1416462380132
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: 7bit

Test mail Send Succesfully
------=_Part_3_47905596.1416462380132--

Это код, который я использую.

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
String subject = "Test Subject";
String msgContent = "Test mail Send Succesfully";
String senderName = "Jos";
String password = "XXXXXXXXXXX";
String fromEmail = "xxxxxxxxx@gmail.com";
String toEmail = "YYYYYYYYYYY@gmail.com";
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
});
Message message = new MimeMessage(session);
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(msgContent, "utf-8");
Multipart multiPart = new MimeMultipart("alternative");
multiPart.addBodyPart(textPart);
message.setContent(multiPart);
message.setFrom(new InternetAddress(fromEmail, senderName));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(toEmail));
message.setSubject(subject);
message.setSentDate(new Date());
Transport.send(message);

ДОБАВЛЕННОЕ СООБЩЕНИЕ DEBUG без использования multipart

Loading javamail.default.providers from jar:file:/my-web/WEB-INF/lib/mail-1.4.7.jar!/META-INF/javamail.default.providers
DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Oracle, version=null
DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Oracle, version=null
DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Oracle, version=null
DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Oracle, version=null
DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Oracle, version=null
DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Oracle, version=null
Loading javamail.default.providers from jar:file:/my-web/WEB-INF/lib/mail-1.4.jar!/META-INF/javamail.default.providers
DEBUG: loading new provider protocol=imap, className=com.sun.mail.imap.IMAPStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=imaps, className=com.sun.mail.imap.IMAPSSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtp, className=com.sun.mail.smtp.SMTPTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=smtps, className=com.sun.mail.smtp.SMTPSSLTransport, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3, className=com.sun.mail.pop3.POP3Store, vendor=Sun Microsystems, Inc, version=null
DEBUG: loading new provider protocol=pop3s, className=com.sun.mail.pop3.POP3SSLStore, vendor=Sun Microsystems, Inc, version=null
DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type@17c7ee05; class=com.sun.mail.smtp.SMTPTransport; vendor=Oracle
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP uj7sm1724517pac.4 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO localhost
250-mx.google.com at your service, [201.140.200.84]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO localhost
250-mx.google.com at your service, [201.140.200.84]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<xxxxxxxxxxx@gmail.com>
250 2.1.0 OK uj7sm1724517pac.4 - gsmtp
RCPT TO:<yyyyyyy@gmail.com>
250 2.1.5 OK uj7sm1724517pac.4 - gsmtp
DEBUG SMTP: Verified Addresses
DEBUG SMTP: yyyyyyy@gmail.com
DATA
354 Go ahead uj7sm1724517pac.4 - gsmtp

Test mail Send Succesfully
.
250 2.0.0 OK 1416479656 uj7sm1724517pac.4 - gsmtp
QUIT
221 2.0.0 closing connection uj7sm1724517pac.4 - gsmtp

ДОПОЛНИТЕЛЬНОЕ СООБЩЕНИЕ DEBUG с multipart

DEBUG: getProvider() returning provider protocol=smtp; type=javax.mail.Provider$Type@17c7ee05; class=com.sun.mail.smtp.SMTPTransport; vendor=Oracle
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 587, isSSL false
220 mx.google.com ESMTP yl6sm1684572pbc.91 - gsmtp
DEBUG SMTP: connected to host "smtp.gmail.com", port: 587

EHLO localhost
250-mx.google.com at your service, [201.140.200.84]
250-SIZE 35882577
250-8BITMIME
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 Ready to start TLS
EHLO localhost
250-mx.google.com at your service, [201.140.200.84]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "35882577"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER"
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN succeeded
DEBUG SMTP: use8bit false
MAIL FROM:<xxxxxxxxx@gmail.com>
250 2.1.0 OK yl6sm1684572pbc.91 - gsmtp
RCPT TO:<yyyyyyy@gmail.com>
250 2.1.5 OK yl6sm1684572pbc.91 - gsmtp
DEBUG SMTP: Verified Addresses
DEBUG SMTP: yyyyyyy@gmail.com
DATA
354 Go ahead yl6sm1684572pbc.91 - gsmtp

------=_Part_1_1348144858.1416480282126
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 7bit

Test mail Send Succesfully
------=_Part_1_1348144858.1416480282126--
.
250 2.0.0 OK 1416480266 yl6sm1684572pbc.91 - gsmtp
QUIT
221 2.0.0 closing connection yl6sm1684572pbc.91 - gsmtp

спросил(а) 2021-01-25T20:15:50+03:00 4 месяца, 4 недели назад
1
Решение
63

РЕДАКТИРОВАТЬ

Следующая ссылка описывает причину этой проблемы

http://yfrankfeng.blogspot.in/2012/07/java-mail-does-not-set-subject-problem.html

Проверьте, существует ли зависимость org.apache.openejb

Попробуйте установить кодировку объекта

message.setSubject(subject,"utf-8");

ответил(а) 2021-01-25T20:15:50+03:00 4 месяца, 4 недели назад
45

Попробуй это

Файл Java

class MailClient
extends Authenticator {

public static final int SHOW_MESSAGES = 1;
public static final int CLEAR_MESSAGES = 2;
public static final int SHOW_AND_CLEAR
= SHOW_MESSAGES + CLEAR_MESSAGES;
public static String SMTP_AUTH_USER = "";
public static String SMTP_AUTH_PWD = "";

protected String from;
protected Session session;
protected PasswordAuthentication authentication;

public MailClient(String user, String pass, String host, String port) {
this(user, pass, host, port, false);
}

public MailClient(String user, String pass, String host, String port, boolean debug) {
from = user;//user + '@' + host;
SMTP_AUTH_USER = user;
SMTP_AUTH_PWD = pass;
// authentication = new PasswordAuthentication(user, pass);
Properties props = new Properties();
props.put("mail.user", user);
props.put("mail.host", host);
props.put("mail.port", port);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");//
props.put("mail.debug", debug ? "true" : "false");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");

//props.put("mail.smtp.starttls.enable","true" );
// props.put("mail.smtp.socketFactory.port", port);
// props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
Authenticator auth = new SMTPAuthenticator();

session = Session.getInstance(props, auth);
// System.out.println("mail session created");
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return authentication;
}

public void sendMessage(
String to, String subject, String content, String from)
throws Exception {
//InternetAddress[] replyToAddress = new InternetAddress[1];
//replyToAddress[0] = new InternetAddress(reply);

//System.out.println("SENDING message from " + from + " to " + to);
//System.out.println();

MimeMessage msg = new MimeMessage(session);

msg.setFrom(new InternetAddress(from, "test"));

msg.addRecipients(Message.RecipientType.TO, to);

//msg.setReplyTo(replyToAddress);
msg.setSubject(subject);

msg.setText(content);

msg.setContent(content, "text/html");

Transport.send(msg);

// System.out.println("Mail sent");
}
private class SMTPAuthenticator extends javax.mail.Authenticator {
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
}
} } public class Mail {
static MailClient client;
public static boolean SendGMail(final String username, final String password, String host, String port, String recipientEmail, String subject, String message) throws AddressException, MessagingException {
boolean status = false;
client = new MailClient(username, password, host, port);
try {
client.sendMessage(recipientEmail, subject, message, username);
status = true;
} catch (Exception ex) {
ex.printStackTrace();
Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, null, ex);
}
return status;
} }


Функция вызова

Mail.SendGMail(appMail, appMailPwd, mailHost, mailPort, mailid, mailSubject, message);

ответил(а) 2021-01-25T20:15:50+03:00 4 месяца, 4 недели назад
Ваш ответ
Введите минимум 50 символов
Чтобы , пожалуйста,
Выберите тему жалобы:

Другая проблема