error: package sun.net.smtp is not visible - java

We are moving some old code to java11.We are creating a smtp client. The coe compilation fails when we use java11.
error: package sun.net.smtp is not visible
[javac] sun.net.smtp.SmtpClient SMTP = new sun.net.smtp.SmtpClient(SMTP_SERVER);
[javac] ^
[javac] (package sun.net.smtp is declared in module java.base, which
does not export it)
looks like smtp package support is removed from the java11. Any suggestions will be helpful.
Regards,
Akj

You can use JavaMail API to send email to get this sorted. Go to below link and download the .jar file and add to your project. If not you can add it as a maven dependency.
https://mvnrepository.com/artifact/javax.mail/mail/1.4.7
A sample code to talk to SMTP server and send email as per below.
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("abc#abcmail.com"));
message.setRecipients(
Message.RecipientType.TO, InternetAddress.parse("to#abcmail.com"));
message.setSubject("Mail Subject");
String msg = "This is a sample email ";
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(msg, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(mimeBodyPart);
message.setContent(multipart);
Transport.send(message);
Your configurations can be done with a Java Properties object
Properties prop = new Properties();
prop.put("mail.smtp.auth", true);
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", "smtp.abcmail.com");
prop.put("mail.smtp.port", "25");
prop.put("mail.smtp.ssl.trust", "smtp.abcmail.com");

You should use JavaMail, a Java API for sending and receiving emails via SMTP, POP3, and IMAP.
First, have a look at Oracle docs about sending mail in Java here
The sample code below is extracted from the Oracle docs and illustrate how you should send email using the JavaMail API.
Properties props = new Properties();
props.put("mail.smtp.host", "my-mail-server");
Session session = Session.getInstance(props, null);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom("me#example.com");
msg.setRecipients(Message.RecipientType.TO,
"you#example.com");
msg.setSubject("JavaMail hello world example");
msg.setSentDate(new Date());
msg.setText("Hello, world!\n");
Transport.send(msg, "me#example.com", "my-password");
} catch (MessagingException mex) {
System.out.println("send failed, exception: " + mex);
}
Also, note that to send a mail with Java Mail you need a valid SMTP server and an account in that server.

Related

How to fix 'Could not convert socket to TLS' error in java

I was using the JavaMail API to send an email containing a text file. This code I wrote was working perfectly fine last week, however I logged on today and ran the program and received the error in the image I've attached at the bottom. I updated to the newest version of java 8 and still receive this error. (I have to use java 8 for the project for work) I looked at the java 8 patch notes for this update and saw the removed of root CA Certificates and I'm not sure what to think/do. I am posting this question because I cannot find any solution in the other tons of questions about this.
I am running Java 8 (jre 1.8.0_221) and previously was running jre 1.8.0_211. I do not know what changed as it stopped working today with v.211 and is also not working after I updated to the most recent version of Java 8 with v.221. I have tried various other properties with no success. I'm not sure if it is the Java removal of something specific (which I doubt) or if it has to do with firewall permissions any smtp permissions I may or may not have. Anyways, the code is below for the email sending portion and the code fails at Transport.send(message); with error "Could not convert socket to TLS"
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
props.put("mail.smtp.debug", "true");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtpUsername, u2);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(prop.getProperty("Message"));
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(prop.getProperty("Message"));
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(prop.getProperty("text") + ".txt");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(prop.getProperty("filename"));
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sent successfully.\n");
Error Message I am receiving. Hopefully I have explained thoroughly enough. This is only my second question I've asked on here. Any help is appreciated, thanks.
I am not an expert, but...
You may be impacted by intentional distrusting of some root certificates in April 2019, or whenever they were applied in your environment (re: https://blogs.oracle.com/java-platform-group/jdk-distrusting-symantec-tls-certificates).

Did not received mail using Java Mail API

I want to write a program which can send mail. I created a VM and installed Windows Server 2012 in it and configured it's SMTP Server. Now when I am trying to send email through my program, I am not getting any exception, also I am not receiving the mail. I found that the mail I sent was received by the SMTP server and it was in it's mailroot/Queue Folder. Following is the code.
String to = "shreyaskothari#gmail.com";
String from = "shreyaskothari#gmail.com";
String host = "// VM IP Address";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject("First Email from Java");
message.setText("Hello, This is first email from a Java Program");
Transport.send(message);
System.out.println("Message Sent");
}
catch(Exception e){
e.printStackTrace();
}
VM was not connected to Internet. Once VM got connected to Internet, I received the mail.

javamail attach "noname" from inside Tomcat

I'm trying to send an email using javamail inside a web application using TomEE. My problem is that when I attach a file such as a PDF, the file that I recive is named "noname". Also I don't recieve the body text.
As an observation, if I execute my code from a "main" program (in an other project), the email is sent perfectly. Here is the code:
public class EnviaCorreo{
static Properties mailServerProperties;
static Session getMailSession;
static MimeMessage generateMailMessage;
public void generateAndSendEmail() throws AddressException, MessagingException {
System.out.println("\n 1st ===> setup Mail Server Properties..");
mailServerProperties = System.getProperties();
mailServerProperties.put("mail.smtp.port", "587");
mailServerProperties.put("mail.smtp.auth", "true");
mailServerProperties.put("mail.smtp.starttls.enable", "true");
System.out.println("Mail Server Properties have been setup successfully..");
System.out.println("\n\n 2nd ===> get Mail Session..");
getMailSession = Session.getDefaultInstance(mailServerProperties, null);
generateMailMessage = new MimeMessage(getMailSession);
generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("xxx#gmail.com"));
generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("yyy#gmail.com"));
generateMailMessage.setSubject("Foo store has bought strawberries");
MimeMultipart multiParte = new MimeMultipart();
BodyPart adjunto = new MimeBodyPart();
adjunto.setDataHandler(new DataHandler(new FileDataSource("/home/foo/Desktop/FooProject/src/main/resources/fruit/6781430324446945.pdf")));
adjunto.setFileName("readme.pdf");
BodyPart texto = new MimeBodyPart();
texto.setText("Success!!");
multiParte.addBodyPart(texto);
multiParte.addBodyPart(adjunto);
generateMailMessage.setContent(multiParte, "text/html");
System.out.println("Mail Session has been created successfully..");
System.out.println("\n\n 3rd ===> Get Session and Send mail");
Transport transport = getMailSession.getTransport("smtp");
transport.connect("smtp.gmail.com", "yyy#gmail.com", "foopsswd123()");
transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
transport.close();
}
Bonus
I'm working with TomEE and iText for PDF generation. Where should I put the folder where I save dynamically generated PDFs to?
TomEE uses geronimo javamail (in tomee lib) by default. You can replace it by the version you used in your main and add geronimo-locator and geronimo-registry
http://repo1.maven.org/maven2/org/apache/geronimo/specs/geronimo-osgi-locator/1.1/geronimo-osgi-locator-1.1.jar
and http://repo1.maven.org/maven2/org/apache/geronimo/specs/geronimo-osgi-registry/1.1/geronimo-osgi-registry-1.1.jar as well in libs
If you dont want to change the version maybe use tomee.xml session to get your session injected. I know for gmail you have to provide an authenticator for instance with geronimo javamail

Exception while sending an email in Java with javax.mail

I'm trying to do an Android app that sends an image automatically without any intervention from the user.
I'm using javax.mail jar (and the activation.jar and additional.jar) in order to do so.
I'm doing the following
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.ssl.enable",true);
props.put("mail.smtp.port", "465");
Session session = Session.getInstance(props,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(USER,PASS);
}
});
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("*******#gmail.com"));
message.setSubject("Email Subject");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("******#gmail.com"));
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent("<img src=\"image.gif\"/>","text/html");
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
FileDataSource source = new FileDataSource(new File(ruta));
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("picture.gif");
messageBodyPart.setDisposition("inline");
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
When I execute this code, I get the following error
W/System.err(24907): javax.mail.MessagingException: IOException while sending message;
W/System.err(24907): nested exception is:
W/System.err(24907): javax.activation.UnsupportedDataTypeException: no object DCH for MIME type multipart/mixed;
W/System.err(24907): boundary="----=_Part_0_1095625208.1397499270313"
W/System.err(24907): at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1182)
W/System.err(24907): at javax.mail.Transport.send0(Transport.java:254)
W/System.err(24907): at javax.mail.Transport.send(Transport.java:124)
Any idea on how can I solve this?
I'm using a Debian 64-bits computer and Eclipse Java EE IDE for Web Developers - Kepler. if it's needed for the solution...
DCH is Data Content Handler. MimeType handlers seem to be not configured correctly.
If you can download and use latest 1.5.* version of java mail api, this error should be getting resolved.
Otherwise, within the code you can execute some statements to set the MimeType handlers.
Add following code snippet to your mail module and is available for the mail Session.
MailcapCommandMap mailcapCommandMap = new MailcapCommandMap();
mailcapCommandMap.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed; x-java-fallback-entry=true");
CommandMap.setDefaultCommandMap(mailcapCommandMap);
You can extend this for additional MimeTypes
mailcapCommandMap.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mailcapCommandMap.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mailcapCommandMap.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mailcapCommandMap.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
Refer To:
javax.activation.MailcapCommandMap.addMailcap(java.lang.String)
Add entries to the registry. Programmatically added entries are
searched before other entries.
Apart from this method, read entire documentation on this class.
I had this same problem for my release mode android app, it works as expected for the debug mode.
Adding the following lines in the proguard file will fix the problem:
-keep class com.sun.mail.handlers.**
-dontwarn com.sun.mail.handlers.handler_base

how to send email through outlook from java

i have using the following code for sending mail within a domain.
public void sendMail(String mailServer, String from, String to,
String subject, String messageBody, String[] attachments)
throws MessagingException, AddressException {
// Setup mail server
Properties props = System.getProperties();
props.put("mail.smtp.host", mailServer);
// Get a mail session
Session session = Session.getDefaultInstance(props, null);
// Define a new mail message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// Create a message part to represent the body text
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(messageBody);
// use a MimeMultipart as we need to handle the file attachments
Multipart multipart = new MimeMultipart();
// add the message body to the mime message
multipart.addBodyPart(messageBodyPart);
// add any file attachments to the message
addAtachments(attachments, multipart);
// Put all message parts in the message
message.setContent(multipart);
// Send the message
Transport.send(message);
System.err.println("Message Send");
}
protected void addAtachments(String[] attachments, Multipart multipart)
throws MessagingException, AddressException {
for (int i = 0; i < attachments.length ; i++) {
String filename = attachments[i];
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
// use a JAF FileDataSource as it does MIME type detection
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));
// assume that the filename you want to send is the same as the
// actual file name - could alter this to remove the file path
attachmentBodyPart.setFileName(filename);
// add the attachment
multipart.addBodyPart(attachmentBodyPart);
}
}
but if with the same code i try to send an email outside the domain, say i am sending email from mjsharma#domain.com to mhsharma#gmail,com then it fails and gives me the following error. 550 5.7.1 Rcpt command failed: Mail denied due to site's policy
Am i missing something in the above code.
Please help me
I suspect that's not a problem in your code, but in your mail server (sendmail?) configuration. I would talk to whoever administers your mail infrastructure.
It's likely that your local mail server requires you to authenticate before sending mail out into the world. This is a common policy to prevent spammers from relaying their mail through it.
Assuming your machine has Outlook installed... have you tried using moyosoft's java outlook connector? it's pretty simple to use and passes through network restrictions because it connects to your Outlook application and then sends the mail, so any restriction on smtp ports or servers/proxy policies will be ignored if your Outlook client is working fine.
if you are doing it with command line server-side then i guess this answer is useless for you.
Source: i had similar problem (not same error code, more like an intranet restriction) and using this library solved my problem because of the posted above.

Categories

Resources