email issue with spring and java mail api - spring

My application is now running in websphere 6.1 in AIX box, in which there is a email notification module which works fine till today. The same application is now getting migrated to a Tomcat based cloud platform which is running in a Linux server. The emails are getting sent out from the new Linux based platform to intended recipients, but the email is looking weird with no subject, no recipient email address, attachments are not proper, etc.
Previously it is ant-based build and now i build the project with maven. And i tried to keep same versions of spring and mail api jars.
What could be the issue and what am I doing wrong here? There are no exceptions while sending the email and it is really hard to identify the issue. Appreciate your help and Thanks in advance.
code:
public synchronized void sendwithAttachment(MailMessage mailMessage) throws MailException, MessagingException {
String methodName = "sendwithAttachment";
LogManager.info(LogConstants.NOTIFICATION,
Constants.ENTERING_METHOD + methodName, this.getClass());
try{
MailSender MailSender = (MailSender) mailSender;
Session session = MailSender.getSession();
MimeMessageHelper message = new MimeMessageHelper(new MimeMessage(session), true, "UTF-8");
message.setFrom(mailMessage.getFrom());
message.setTo(mailMessage.getTo());
message.setSubject(mailMessage.getSubject());
message.setSentDate(new Date());
message.setText(mailMessage.getText());
DiskFileAttacher[] diskFileAttachments = mailMessage.getDiskFileAttachments();
for (int i = 0; ((diskFileAttachments != null) && i < diskFileAttachments.length); i++) {
message.addAttachment(diskFileAttachments[i].getAttachmentFilename(), new File(diskFileAttachments[i].getFilePath()));
}
InMemoryFileAttacher[] inMemoryFileAttachments = mailMessage.getInMemoryFileAttachments();
for (int i = 0; ((inMemoryFileAttachments != null) && i < inMemoryFileAttachments.length); i++) {
if(inMemoryFileAttachments[i].getFileObj()!=null){
message.addAttachment(inMemoryFileAttachments[i].getFileName(),
inMemoryFileAttachments[i].getFileObj() );
}else{
message.addAttachment(inMemoryFileAttachments[i].getFileName(),
inMemoryFileAttachments[i]);
}
}
List mimeMessageList = new ArrayList();
mimeMessageList.add(message.getMimeMessage());
MimeMessage[] mimeMessages = (MimeMessage[]) mimeMessageList.toArray(new MimeMessage[mimeMessageList.size()]);
LogManager.info(LogConstants.NOTIFICATION,"before MailSender.send is called " + methodName, this.getClass());
MailSender.send(mimeMessages);
}catch(MailException e){
LogManager.info(LogConstants.NOTIFICATION, "Some exception occured while sending emails...", this.getClass());
}

Check which version of JavaMail you're using. If you're including the JavaMail jar file in your application, there may also be a copy of the GNU version of JavaMail on your Linux system that's being used instead of yours. Look for the libgnumail-java package.

I found the issue and resolved this. I include maven dependency for axiom jars, which has also dependency for "geronimo-javamail_1.4_spec" and this geronimo java mail jars are also downloaded. And while sending emails this geronimo mail api was used instead of original java mail api. I added exclusions and now it is resolved.

Related

Microsoft.Office.Interop.Outlook does not work on web server but works on local machine

I am using below code in the button event, so that user can send mail through self machine outlook directly (nuget Microsoft. Office. Interop.Outlook). Code is working when I am debugging below code in my localhost and send mail from outlook. But problem is when I deployed the code into web server and browse through IE from my work station, mail not send through outlook.
This error message show in log:
Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).
How can I resolve this issue?
Web application reside into web server and users will access the application from IE and then they will send mail through self machine outlook.
public void SendEmailOutlook(string mailToRecipients, string mailCCRecipients, string subjectLine, [Optional] string attachments, string HTMLBody)
{
try
{
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem oMsg = oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
Outlook.Recipients oRecips = oMsg.Recipients;
List<string> oTORecip = new List<string>();
List<string> oCCRecip = new List<string>();
var ToRecip = mailToRecipients.Split(',');
var CCRecip = mailCCRecipients.Split(',');
foreach (string ToRecipient in ToRecip)
{
oTORecip.Add(ToRecipient);
}
foreach (string CCRecipient in CCRecip)
{
oCCRecip.Add(CCRecipient);
}
foreach (string to in oTORecip)
{
Outlook.Recipient oTORecipt = oRecips.Add(to);
oTORecipt.Type = (int)Outlook.OlMailRecipientType.olTo;
oTORecipt.Resolve();
}
foreach (string cc in oCCRecip)
{
Outlook.Recipient oCCRecipt = oRecips.Add(cc);
oCCRecipt.Type = (int)Outlook.OlMailRecipientType.olCC;
oCCRecipt.Resolve();
}
oMsg.Subject = subjectLine;
if (attachments.Length > 0)
{
string sDisplayName = "MyAttachment";
int iPosition = 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
var Sendattachments = attachments.Split(',');
foreach (var attachment in Sendattachments)
{
Outlook.Attachment oAttach = oMsg.Attachments.Add(attachment, iAttachType, iPosition, sDisplayName);
}
}
if (HTMLBody.Length > 0)
{
oMsg.HTMLBody = HTMLBody;
}
oMsg.Save();
oMsg.Send();
oTORecip = null;
oCCRecip = null;
oMsg = null;
oApp = null;
}
catch (Exception e)
{
//print(e.Message);
}
}
Outlook, just like every other Office app, cannot be used from a service (such as IIS).
The Considerations for server-side Automation of Office article states the following:
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.
As a possible workaround you may consider using EWS or any other REST API (for example, Graph API) if you deal with Exchange server profiles only. See Explore the EWS Managed API, EWS, and web services in Exchange for more information.
I've had this issue too."Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))."
Server environment:Windows server 2019&iis
Local machine:Windows 10&iis
Tip:The Microsoft office doesn't support that use OutWork IIS or Asp.net
So,I give you right answer(It's worked):
1、Run "win+R" ,then inuput 'Dcomcnfg'
2、As this pic:
enter image description here

Plaid Link with Java API - Why am I getting 'client_id must be a properly formatted, non-empty string' error

I'm using the official Plaid Java API to make a demo application. I've got the back end working in Sandbox, with their /sandbox/public_token/create generated public keys.
Now, I'm trying to modify the front-end from Plaid's quickstart project to talk with my back end, so I can start using the development tier to work with my IRL bank account.
I'm implementing the basic first step - generating a link_token. However, when the front end calls my controller, I get the following error:
ErrorResponse{displayMessage='null', errorCode='INVALID_FIELD', errorMessage='client_id must be a properly formatted, non-empty string', errorType='INVALID_REQUEST', requestId=''}
This is my current iteration on trying to generate a link_token:
public LinkTokenResponse generateLinkToken() throws IOException {
List<String> plaidProducts = new ArrayList<>();
plaidProducts.add("transactions");
List<String> countryCodes = new ArrayList<>();
countryCodes.add("US");
countryCodes.add("CA");
Response<LinkTokenCreateResponse> response =
plaidService.getClient().service().linkTokenCreate(new LinkTokenCreateRequest(
new LinkTokenCreateRequest.User("test_user_ID"),
"test client",
plaidProducts,
countryCodes,
"en"
).withRedirectUri("")).execute();
try {
ErrorResponse errorResponse = plaidService.getClient().parseError(response);
System.out.println(errorResponse.toString());
} catch (Exception e) {
// deal with it. you didn't even receive a well-formed JSON error response.
}
return new LinkTokenResponse(response.body().getLinkToken());
}
I modeled this after how it seems to work in the Plaid Quickstart's example. I do not see client ID being set explicitly anywhere in there, or anywhere else in Plaid's Java API. I'm at a bit of a loss.
I'm not super familiar with the Java Plaid library specifically, but when using the Plaid client libraries, the client ID is generally set when initializing the client instance. From there, it is automatically included in any calls you make from that client.
You can see the client ID being set in the Java Quickstart here:
https://github.com/plaid/quickstart/blob/master/java/src/main/java/com/plaid/quickstart/QuickstartApplication.java#L67
PlaidClient.Builder builder = PlaidClient.newBuilder()
.clientIdAndSecret(configuration.getPlaidClientID(), configuration.getPlaidSecret());
switch (configuration.getPlaidEnv()) {
case "sandbox":
builder = builder.sandboxBaseUrl();
break;
case "development":
builder = builder.developmentBaseUrl();
break;
case "production":
builder = builder.productionBaseUrl();
break;
default:
throw new IllegalArgumentException("unknown environment: " + configuration.getPlaidEnv());
}
PlaidClient plaidClient = builder.build();

How to change the from address in send grid email

I have configured the send grid API for email service in my spring boot APP. And, it's working fine. I wanted to change the from address as "no-reply#xyz.com" instead of "apikey". But, I couldn't.
Also, I tried it using JavaMaiSender. But, no luck.
Could you please anyone let me know?
public void sendEmailUsingSendgrid(EmailRequest emailRequest) throws IOException {
String text = getEmailTemplate(emailRequest);
SendGrid sg = new SendGrid(sendGridApi);
sg.addRequestHeader("X-Mock", "true");
Request request = new Request();
Mail mail = new Mail();
mail.setFrom(new Email(emailRequest.getFr()));
mail.setSubject(emailRequest.getSbjt());
mail.addContent(new Content("text/html", text));
List<String> mailList = Arrays.asList(emailRequest.getTo());
for (String to : mailList) {
Personalization p1 = new Personalization();
p1.addTo(new Email(to));
mail.addPersonalization(p1);
}
mail.setReplyTo(new Email("noreply#xyz.com"));
request.setMethod(Method.POST);
request.setEndpoint("mail/send");
request.setBody(mail.build());
sg.api(request);
}
Properties
# SENDGRID
sendgrid-api-key=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

GWT Spring Jasper Reports

I have an application built in GWT and Spring. I am trying to generate Jasper Reports on the server side. However when I execute the functionality, it hangs/stops at jasperDesign = JRXmlLoader.load(file_name); and does not respond or throw an exception. This means that my RPC call that triggers the report generation function does not return a response either (so the application hangs). However when I run the function in a normal java application it generates a report without any problem. What could be the issue? I am using JasperReports version 5.6.0. My java function:
public StandardServerResponse printReport(List<Object> items) {
StandardServerResponse response = new StandardServerResponse();
String file_name = null;
Map<String, Object> parameters;
JasperDesign jasperDesign;
JasperReport jasperReport;
JasperPrint jasperPrint;
try {
for (Object obj: items) {
parameters = new HashMap<String, Object>();
parameters.put("id_in", obj.getId());
file_name = "G:\\myreport.jrxml";
jasperDesign = JRXmlLoader.load(file_name); //application stops here
jasperReport = JasperCompileManager.compileReport(jasperDesign);
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource.getConnection());
JasperExportManager.exportReportToPdfFile(jasperPrint, "G:\\report.pdf");
}
response.setSuccess(true);
} catch (Exception ex) {
ex.printStackTrace();
response.setSuccess(false);
}
return response;
}
I finally solved my problem after many long days of debugging :-).
I had these two jars in my WEB-INF/lib folder.
jasperreports-functions-5.6.0-SNAPSHOT.jar
jasperreports-fonts-5.6.0.jar
I removed them and the app worked. I still don't understand why they would cause a problem though.
I also changed my code to work with a .jasper extension and directly called JasperRunManager.runReportToPdfFile(file_name, "S:\\output_report.pdf", parameters, connection);
Thanks a lot Darshan Lila for trying, I really appreciate. Hope this helps someone.

Changing mail configuration in runtime

I've just started to investigate grails framework and first task I'm trying to resolve is sending email. Basic tutorial and community answers provided lot of information for quick start, and yes I've created simple app with possibility to send email. But, next point of my investigation was changing mail configuration in runtime. So, first my configuration in Config.grovy was
grails {
mail {
host = ""
port = 0
username = ""
password = ""
props = [""]
}
}
with values, and all worked corectlly, after that I've tried to re-config it
like that
grailsApplication.config.grails.mail.host = "smtp.gmail.com"
grailsApplication.config.grails.mail.port = 465
grailsApplication.config.grails.mail.username = ""
from controller, and found that mail is sending from old adress, after debugs I've found that there are auto-wired instances in mail plugins like mailSender and one obvious solution is recreate mailSender and re-set it, but judging to Spring singleton policy it will be hard solution, so, My question Are there possibilities to re-configure mail in runtime without class-reloading ?
Thanks.
Fixed using re-init mailsender instance but waiting for other solutions, Thanks
mailSender.setHost("smtp.gmail.com")
mailSender.setPort(465)
mailSender.setJavaMailProperties(new Properties() {
{
put("mail.smtp.auth", "true");
put("mail.smtp.socketFactory.port", "465");
put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
put("mail.smtp.socketFactory.fallback", "false");
}
})
try following way
sendMail {
mailSender.username = 'abc#gmail.com'
mailSender.password = "pwd"
to "nagaraj.s#hotmail.com"
subject "Hi"
message "Hi"
}

Resources