Quantcast
Channel: Active questions tagged email - Stack Overflow

How do I address this "Operation Stopped" (HRESULT) Error Code?

$
0
0

I have a script which extracts email metadata to a spreadsheet. The script works when I apply it to a relatively small email account (~9000 emails). It also works when I apply it to a big email account (~250,000 emails), but set the script to only extract a single metadata field.

It doesn't work when I apply it to the big email account (~250,000 emails) and attempt to extract multiple metadata fields. Instead, it outputs the following error code and an incomplete spreadsheet (only 33,146 emails captured).

Exception from HRESULT: 0xB5940115At C:\file\path\path\name.ps1:15 char:18+     foreach ($item in ($folder |Select-Object -ExpandProperty "I ...++ CategoryInfo     :OperationStopped: (:) [], COMException+ FullyQualifiedErrorID: System.Runtime.InteropServices.COMExceptionException from HRESULT: 0xBBC40115At C:\file\path\path\name.ps1:13 char:14+    foreach ($folder in $ParentFolder.Folders)++ CategoryInfo     :OperationStopped: (:) [], COMException+ FullyQualifiedErrorID: System.Runtime.InteropServices.COMExceptionException from HRESULT: 0xBFE40115At C:\file\path\path\name.ps1:13 char:14+     foreach ($folder in $ParentFolder.Folders)++ CategoryInfo     :OperationStopped: (:) [], COMException+ FullyQualifiedErrorID: System.Runtime.InteropServices.COMException

What I have tried:

  • Googling the error code number. Nothing specific came up.
  • Googling the second line of the error code (FullyQualifiedErrorID). Nothing specific came up.

Here is the script in full. Any help welcome.

function Get-MailFromOutlookFolder{    [CmdletBinding()]    param     (        [Parameter(Mandatory = $true)]        [Object] $ParentFolder    )    $items = @()    foreach ($folder in $ParentFolder.Folders)    {        foreach ($item in ($folder | Select-Object -ExpandProperty "Items"))        {             if ($item.Class -eq 43)            {                # process email                $PR_SMTP_ADDRESS = "http://schemas.microsoft.com/mapi/proptag/0x39FE001E"                #$smtpAddress = $item.PropertyAccessor.GetProperty($PR_SMTP_ADDRESS)                $items += $item | Select-Object -Property "ConversationTopic", "ReceivedTime", "SenderName", "ReceivedByName", "BCC", "CC","Size", "SenderEmailAddress", @{ "Label" = "Folder"; "Expression" = { $_.Parent.Name } }, @{name="Attachments";expression={$_.Attachments|%{$_.DisplayName}}}            }        }        # process (sub)folder items        $items += Get-MailFromOutlookFolder -ParentFolder $folder    }    return $items    }$outlook     = New-Object -Com "Outlook.Application"$mapi        = $outlook.GetNamespace("MAPI")$recipient = $mapi.CreateRecipient("name@domain.ca")$folder = $mapi.GetSharedDefaultFolder($recipient, [Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox).Parent$folder1 = $folder.parent.folders('Online Archive - name@domain.ca')$results = Get-MailFromOutlookFolder -ParentFolder $folder1$results | Export-Csv -Path "C:\Fakefolder\email_account_name_2025-06-20.csv"

GreenMail not returning BCC recipient addresses

$
0
0

I'm using GreenMail in a test to verify that our application is sending email correctly.

I start GreenMail with:

GreenMail greenMailServer = new GreenMail(new ServerSetup(port, "localhost", ServerSetup.PROTOCOL_SMTP));greenMailServer.start();

I have a separate process that sends the email to the GreenMail SMTP server (this is part of an integration test), so my test code waits for the email with:

long endTime = System.currentTimeMillis() + timeout;// Get the fake mail server and listen for messagesGreenMail mailServer = ITester.getFakeEMail();while(System.currentTimeMillis() < endTime)  {     boolean timedOut = !mailServer.waitForIncomingEmail(endTime - System.currentTimeMillis(), 1);     if(timedOut) {          throw new TestFailure(lineNumber, "Timed out waiting for email To: '"+to+"' Subject: '"+subject+"' Body: '"+body+"' .");     }     for(MimeMessage message : mailServer.getReceivedMessages()) {          try {              StringBuilder errors = new StringBuilder();              // Check who the message is going to              //Address[] allRecipients = message.getRecipients(Message.RecipientType.BCC);              Address[] allRecipients = message.getAllRecipients();

I've tried both the commented out request for Recipients and the getAllRecipients, but I always receive null. I've verified that my application is sending the email to one address in the BCC field.

Any idea why I'm not seeing the recipient email address?

PySpark dataframe to Excel Email attachment with sheet name

$
0
0

I'm unable to send PySpark data frame as an attachment in Excel.

I'm able to do easily with CSV file using below,

email.add_attachment(df.toPandas().to_csv(index=False).encode('utf-8'), maintype='application', subtype='csv', filename=file)

Unable do the same using Excel,

email.add_attachment(df.toPandas().to_excel(file, index=False, sheet_name='FileReport'))

Below is the code

from datetime import datetime, date import pandas as pd from pyspark.sql import Row from pyspark.sql import SparkSession spark = SparkSession.builder.getOrCreate() from email.message import EmailMessageemail = EmailMessage()email['From'] = "dkfhskg"email['To'] = "dsjagjsg"email['Subject'] = "Report"mail = 'Report'email.set_content(mail , subtype='html')_smtp_server = "kdfhsajgfjdsg"_smtp_port = 10smtp = smtplib.SMTP(_smtp_server, _smtp_port)df = spark.createDataFrame([     Row(Sno=1, Rank=4., RollNo='1000', Date=date(2000, 8, 1),         e=datetime(2000, 8, 1, 12, 0)),     Row(Sno=2, Rank=8., RollNo='1001', Date=date(2000, 6, 2),          e=datetime(2000, 6, 2, 12, 0)),     Row(Sno=4, Rank=5., RollNo='1002', Date=date(2000, 5, 3),         e=datetime(2000, 5, 3, 12, 0)) ]) file = 'Report_'+ str(datetime.now()) +'.xlsx'email.add_attachment(df.toPandas().to_excel(file, index=False, sheet_name='FileReport'))

SMTP dot stuffing.. when and where to do it?

$
0
0

I have found conflicting information about dot stuffing when transmitting an email.

  1. stuff a dot if the line contains a single dot (to avoid premature termination)
  2. stuff a dot to every line that starts with a dot
  3. stuff a dot to (1) and to every line part of a quoted-printable message part

Can anyone clarify?

DKIM Body Hashing

$
0
0

I want to verify a E-Mail based on the DKIM Signature. I can't replicate the body hash for the mails. These are Test-mails from me, which are legit. The point of failure in my opinion is the use of Multipart.

When i send a Simple Text Email it is easy to compute the body hash...In the RFC i couldn't find anything regarding multipart. Does any one know if there is a special case (ChatGPT had a take on preamble CLRF for the body, but i couldn't find anything useful to back it up).

I already wrote a canonization script:

#!/usr/bin/env python3"""Canonicalise the BODY of an RFC-5322 message according toRFC 6376 §3.4.4 (relaxed) and copy the header block unchanged.usage:  dkim_relaxed_body.py  <input.eml>  [output.eml]"""import sys, re, os, hashlib, base64, pathlib# ---------- helpers ----------------------------------------------------_BS = b'[ \t]+'          # WSP = SPACE or HT (only!)def canon_body(body: bytes) -> bytes:"""RFC 6376 relaxed body-canonicalisation."""    # split on CRLF / LF / CR    lines = re.split(br'\r?\n', body)    print(lines)    # 1+2  WSP rules per line    for i, ln in enumerate(lines):        ln = re.sub(br'[ \t]+$', b'', ln)      # trim trailing WSP        ln = re.sub(_BS, b'', ln)             # collapse runs -> one SP        lines[i] = ln    # 3   drop empty lines at end    while lines and lines[-1] == b'':        lines.pop()    # 4   join with CRLF, append exactly one final CRLF    return b'\r\n'.join(lines) + b'\r\n'def body_hash(b: bytes) -> str:    return base64.b64encode(hashlib.sha256(b).digest()).decode()def main() -> None:    if len(sys.argv) < 2:        sys.exit("usage: dkim_relaxed_body.py <input.eml> [output.eml]")    inp = pathlib.Path(sys.argv[1]).expanduser()    if not inp.is_file():        sys.exit(f"input not found: {inp}")    if len(sys.argv) == 3:        out = pathlib.Path(sys.argv[2]).expanduser()    else:        base = inp.stem        ext  = inp.suffix        out  = inp.with_name(f"{base}_mod{ext}")    raw = inp.read_bytes()    # header/body delimiter = first empty line (CRLF CRLF or LF LF)    m = re.search(br'\r?\n\r?\n', raw)    if not m:        sys.exit("no header/body delimiter found")    hdr = raw[:m.end()]        # incl. blank line    bdy = raw[m.end():]    canon_bdy = canon_body(bdy)    print(canon_bdy)    out.write_bytes(hdr + canon_bdy)    with open("temp.bdy.raw", "wb")  as fileHandle:        fileHandle.write(canon_bdy)    print(f"written: {out}")    print("body-hash:", body_hash(canon_bdy))if __name__ == '__main__':    main()

I am verifying with the jdkim library:

import java.io.*;import java.nio.charset.StandardCharsets;import java.nio.file.Files;import java.nio.file.Path;import java.security.*;import java.security.interfaces.RSAPublicKey;import java.security.spec.*;import java.util.*;import java.util.regex.*;import jakarta.mail.*;import jakarta.mail.internet.*;import javax.naming.directory.*;import org.apache.james.jdkim.DKIMVerifier;import org.apache.james.jdkim.api.PublicKeyRecordRetriever;import org.apache.james.jdkim.api.Result;import org.apache.james.jdkim.api.SignatureRecord;import org.apache.james.jdkim.exceptions.PermFailException;import org.apache.james.jdkim.exceptions.TempFailException;import org.apache.james.jdkim.impl.DNSPublicKeyRecordRetriever;public class VDKIM {    public static void checkSignature(String path) throws Exception{        DKIMVerifier verifier = new DKIMVerifier(new DNSPublicKeyRecordRetriever());        List<Result> results = Collections.emptyList();        try{            InputStream stream = new FileInputStream(path);            verifier.verify(stream);            results = verifier.getResults();        }catch(Exception e){            System.out.println("Verification Error: " + e.toString());            results = verifier.getResults();        }finally{            System.out.println("Printing results....");            for(Result e : results){                System.out.println(e.toString());                System.out.println(new String(Base64.getEncoder().encode(e.getRecord().getBodyHash())));            }        }    }    public static void main(String[] args) {        try{            String[] files = new String[]{"raw_fetched_v5.eml"};            for(String s : files){                System.out.println("[*] Testing for file: " + s);                checkSignature(s);                System.out.println();            }        }catch(Exception e){            System.err.println(e.toString());        }

Like already mentioned the only way i got a valid verification is a simple text E-Mail.

SendGrid Link Branding gives ssl issue

$
0
0

Unfortunately, nobody is responding to my support ticket so I think it's a problem needs someone with experience with sendgrid

the reproduction is simple:

  1. did the Domain Authentication and Link Branding

  2. Added all the necessary record to my DNS configs

  3. All verified in SendGrid dashboard.

  4. Tried sending an email and click on the link it gives me this

enter image description here

Configuration of EmailJS works in localhost but not in production

$
0
0

I am developing a project with Vue.js, so to manage sending email through the contact form instead of the backend, I am using Email.js. I followed steps as below:

  1. Add an email services
  2. Create an email template
  3. Install EmailJS
  4. Create contact form

I hosted it on Netlify. Problem is, the sending email works on localhost and in the permalink on Netlify, but not in the production deploy:enter image description hereAnyone have any idea why the EmailJS works properly in the localhost and in the permalink but not in the production deploy?

This is my contact form:

<template><form class="contact-form" @submit.prevent="submitForm"><div class="form-row"><input type="text" placeholder="Emri" v-model="form.name" required /><input type="text" placeholder="Mbiemri" v-model="form.surname" required /></div><input type="email" placeholder="Emaili" v-model="form.email" required /><input type="tel" placeholder="Numri i telefonit" v-model="form.phoneNumber" required /><textarea placeholder="Mesazhi juaj..." v-model="form.message" required></textarea><label class="form-checkbox"><input type="checkbox" id="agree" v-model="form.agree" required /><span class="checkmark"></span>            Unë pajtohem me politikën e privatësisë</label><button type="submit">Dërgo mesazhin</button></form></template>
<script>import emailjs from 'emailjs-com';export default {    data() {        return {            form: {                name: '',                surname: '',                email: '',                phoneNumber: '',                message: '',                agree: false            }        };    },    methods: {        submitForm() {            if (!this.form.agree) {                alert('Ju duhet të pajtoheni me politikën e privatësisë.');                return;            }            emailjs.init('PUBLIC_KEY');            const templateParams = {                from_name: `${this.form.name} ${this.form.surname}`,                from_email: this.form.email,                phone: this.form.phoneNumber,                message: this.form.message            };            emailjs.send('SERVICE_ID',       'TEMPLATE_ID',                      templateParams,'PUBLIC_KEY'            ).then(() => {                alert('Mesazhi u dërgua me sukses!');                this.resetForm();            }).catch((error) => {                console.error('Gabim gjatë dërgimit:', error);                alert('Ndodhi një gabim gjatë dërgimit.');            });        },        resetForm() {            this.form = {                name: '',                surname: '',                email: '',                phoneNumber: '',                message: '',                agree: false            };        }    }};</script>

I tried to check if the email service, email template, account is OK or maybe has any mistake, but their configuration is ok.

PHP mail() function will not send to gmail but will send to my non-gmail account

$
0
0

For some reason the php mail() function is not working properly on a site I am building. I tried to troubleshoot the issue down to its simplest form, and came up with this file:

<?phpmail('myEmail@gmail.com', 'the subject', 'the message', 'From: webmaster@example.com', '-fwebmaster@example.com');?>

when myEmail is a Gmail account, I never receive the message. However when I use a non-gmail account, I do receive the message. I am at a loss and have tried everything to figure this out. I am starting to think it is an obscure host/server issue. You can see the server specs here: http://aopmfg.com/php.php

Any ideas?

EDIT - let me also add that this was all working fine a few weeks ago, the last time I tested it. No significant code changes since then at all.

EDIT 2 - After reading a similar post I tried adding From and Reply-To headers... still no luck. New code:

<?$headers = 'From: <some@email.com>' . "\r\n" .'Reply-To: <some@email.com>';mail('<myEmail@gmail.com>', 'the subject', 'the message', $headers,'-fwebmaster@example.com');?>

Why declare viewport in html email campaign?

$
0
0

The majority of HTML emails and boilerplate that I've seen coded by other people, always declare a viewport meta tag.

I mindfully always avoid declaring a viewport and strive for a very high level of cross/backwards compatibility.

Declaring viewport settings render the email totally unusable for any of your audience using a Blackberry and overall is very poorly supported by any client.

Is there a reason to use this tag that I missed? Why are the majority of other peoples emails I see using this?


Additional Reference: http://www.emailonacid.com/blog/details/C13/emailology_viewport_metatag_rendered_unusable

How Do I save my composed email content as (.eml) before sending in vb.net

$
0
0

I am using the sample code below in sending emails. How can i save it first as an eml file before sending it as email in vb.net

Dim SmtpServer As New SmtpClient("smtp.exampledomain.com", 25) Dim mails As New MailMessage("user@exmple.com", "someuser", "TEST EMAIL", "Sample Message")    SmtpServer.Credentials = New Net.NetworkCredential(user@exmple.com, "password")SmtpServer.Send(mails)

Any suggestion is highly appreciated.Thank you.!

How to avoid Spam in Outlook/Hotmail with Mailgun?

$
0
0

I'm using Mailgun to send transactional emails (tickets for events) and all the emails are sent to Outlook/Hotmail spam and I want to avoid that. I have added the SPF and DKIM records and nothing works. What should I do to avoid the spam filter (actually, I'm not sending spam. The user triggers the transactional email when he register to an event)

Client client = Client.create ();client.addFilter ( new HTTPBasicAuthFilter ( "api", "MI_API_KEY" ) );WebResource webResource = client        .resource ( "MAILGUN_URL" );MultivaluedMapImpl formData = new MultivaluedMapImpl();formData.add ( "from", "hola@peewah.co" );formData.add ( "to", "csacanam@outlook.com" );formData.add ( "subject", "Camilo, welcome to the event" );formData.add ( "html", "<h1>Camilo thank you for your registration in the event</h1>") );formData.add ( "text", "Camilo thank you for your registration in the event" );ClientResponse clientResponse = webResource.type ( MediaType.APPLICATION_FORM_URLENCODED )        .post ( ClientResponse.class, formData );int status = clientResponse.getStatus ();if ( status >= 400 ){    throw new BadRequestException ( "Your message couldn't be sent" );}

Firefox does not accept e-mail whith blank space on end

$
0
0

I would like to make my website work identically on every browser. Unfortunately, the validation mechanism introduced their differences.

Field of type 'e-mail' on Chrome and Opera 'trim';delete blank spaces on input of e-mail field and Firefox no cuts signs and do not accept e-mail in this form.

<input type="email" id="e-mail" class="" name="e-mail" value="" placeholder="" autocomplete="off">

Example:

enter image description here

How to send S/MIME email with MIME headers set to smime.p7m but actual attachment filename as timestamped .edi in PHP?

$
0
0

I'm trying to send a secure EDI email to the ABF via SMTP using PHP. The content must be encrypted and signed using S/MIME (PKCS#7).

Here's what ABF requires:

The MIME headers of the attachment must be:

MIME-Version: 1.0Content-Disposition: attachment; filename="smime.p7m"Content-Type: application/x-pkcs7-mime; smime-type=enveloped-data; name="smime.p7m"Content-Transfer-Encoding: base64

However, when the recipient downloads the attachment, the file should be named something like:AA*****_202504021256.edi

How can I send an encrypted S/MIME email where:

MIME headers show the filename as smime.p7m, as required by the recipient

But the downloaded attachment is named like AA*****_202504021256.edi?

I use openssl_pkcs7_sign() and openssl_pkcs7_encrypt() in PHP to generate the .p7m file

$mail->addAttachment(' AA*****_202504021256.edi', 'smime.p7m', 'base64', 'application/x-pkcs7-mime; smime-type=enveloped-data');

Email HTML development - Hiding Interactive Content for Gmail

$
0
0

I have a tap to reveal element in my email for webkit based clients. There is a fallback set up for Outlook and Gmail. However, the Gmail fallback is showing both the fallback and the first tap to reveal image below it. There are no issues with Outlook showing fallback and interactivity working in Apple Mail. See the code below:

<style>/* Fallback visible by default */.fallback {    display: block;    max-width: 500px;    margin: 0 auto;    height: 300px;}.content,input[type="radio"] {    display: none;    mso-hide: all;}/* Gmail fallback override */u ~ div .content {    display: none !important;    max-height: 0 !important;    overflow: hidden !important;}u ~ div .fallback {    display: block !important;    max-height: none !important;}/* WebKit-only interactivity */@media screen and (-webkit-min-device-pixel-ratio:0) {    .fallback {        display: none !important;        mso-hide: all !important;    }    .content {        display: block !important;    }    input[type="radio"] {        display: inline-block !important;    }    .tap {        display: block !important;        mso-hide: all !important;    }    .reveal {        display: none !important;    }    #tapreveal:checked ~ .content .reveal-1 {        display: block !important;    }    #tapreveal2:checked ~ .content .reveal-2 {        display: block !important;    }    /* Ensure the tap image is hidden once interacted with */    #tapreveal:checked ~ .content .tap {        display: none !important;    }}.content {    position: relative;    max-width: 500px;    margin: 0 auto;    height: 300px;    overflow: hidden;}.tap,.reveal {    position: absolute;    top: 0;    left: 0;    width: 100%;    height: 100%;    display: block;    z-index: 1;}.tap img,.reveal img {    width: 100%;    height: auto;    display: block;    max-width: 100%;    margin: 0;}</style><!-- Fallback Image (shown by default and in Outlook) --><table width="100%" bgcolor="#ffffff" cellpadding="0" cellspacing="0" border="0"><tr><td align="center"><table width="500" cellpadding="0" cellspacing="0" border="0"   class="fallback"><tr><td><a href="xx"><img src="xx" width="500" style="display:block; border:0;  width:100%; max-width:500px; height:auto; font-family: Arial, sans-serif; font-size: 16px; line-height: 20px; color: #000000;" alt="xx"></a></td></tr></table></td></tr>
<!--[if !mso]><!-- --><!-- Interactive Tap Logic (WebKit only) --><input type="radio" name="tapreveal" id="tapreveal" style="display:none!important;"><input type="radio" name="tapreveal" id="tapreveal2" style="display:none!important;"><div class="content"><!-- Step 1: Initial tap image --><label for="tapreveal" class="tap" style="cursor: pointer;"><img src="xx" alt="xx"></label><!-- Step 2: Tap 1 --><div class="reveal reveal-1" style="display: none;"><a href="xx" class="tap-2" style="display:block;"><img src="xx" alt="Final Offer Reveal"></a></div>

How to send an email using sendmail command in linux

$
0
0

I tried the below two commands.

  1. From: mail_idTo: Recipient_mail_idHi, this is my message, and I'm sending it to you!.
  2. echo "My message" | sendmail -s subject Recipient_mail_id

But didn't get any mail to the recipient's mail address.

SMTP server is installed on another server and it is up and running. So can anyone help me out on how to send a test email through that SMTP server using sendmail or smtp commands?


How to implement Odoo login authentication using OTP sent via email (instead of password)?

$
0
0

I'm trying to implement a custom login mechanism in Odoo where users authenticate using an OTP (One-Time Password) sent to their email, instead of the traditional username/password method.

My goal:

  1. User enters their email address on the login screen.
  2. An OTP is generated and sent to their email.
  3. User enters the OTP, and if it’s valid and not expired, they are logged in.

What I’ve tried:

  • Created a custom controller with @http.route('/web/login/request_otp', ...) to handle OTP generation.
  • Stored OTPs in a new model (res.users.otp) with expiry timestamp.
  • Used mail.template to send OTP to the user’s email.
  • Created another route to validate the OTP and authenticate using request.session.authenticate(...).

Issue:

When I try to access /web/login/request_otp?email=test@example.com, I get a 404 Not Found error.
I'm not sure if:

  • The route is properly registered.
  • The controller is loaded correctly.
  • The module was upgraded properly.

Environment:

  • Odoo version: 16 (also trying on 17)
  • Custom module created under addons/
  • SMTP is configured and working for other mail templates

My questions:

  1. What's the correct way to register a custom public HTTP route for login in Odoo?
  2. How to properly authenticate a user from a controller using OTP (without requiring password)?
  3. Any security concerns or best practices I should follow when implementing OTP login in Odoo?

Any help or working example would be appreciated 🙏

pear fatal Error: Class 'Mail' not found .wamp

$
0
0

I am having some trouble with using the send mail functionality of pear with wamp. I went through with the steps in this link : (http://pear.php.net/manual/en/installation.checking.php) to check if my pear was installed correctly, and it seems like I have it right.

<?phprequire_once 'System.php';var_dump(class_exists('System', false));?>

The code above returns bool(true). So I am assuming that my paths are set right.But for the code below I am getting an error.

<?php        include 'Mail.php';    include 'Mail/mime.php' ;    $text = 'Text version of email';    $html = '<html><body>HTML version of email</body></html>';    $file = 'test.xls';    $crlf = "\n";    $hdrs = array('From'    => 'myemail@gmail.com','Subject' => 'Test mime message'                  );    $mime = new Mail_mime(array('eol' => $crlf));    $mime->setTXTBody($text);    $mime->setHTMLBody($html);    $mime->addAttachment($file, 'text/plain');    $body = $mime->get();    $hdrs = $mime->headers($hdrs);    $mail =& Mail::factory('mail');    $mail->send('myemail2@gmail.com', $hdrs, $body);?>

Error is on this line : $mail =& Mail::factory('mail'); . Fatal error: Class 'Mail' not found

Also, I installed pear Mail with this command : pear install Mail Mail_mime

I would appreciate any help.

Thanks,

Sending Email Via Kotlin

$
0
0

I am using the code below to send an email but it is asking for gmail credentials. I am looking for a command, something similar to mailx, to send emails to a particular address without asking for any credentials. Any help is appreciated.

Code

class MainActivity : AppCompatActivity() {    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)        val button: Button = findViewById(R.id.button)        val editTextTo: EditText = findViewById(R.id.editTextTo)        button.setOnClickListener(View.OnClickListener {            val to = editTextTo.getText().toString()            val subject = "Test"            val message = "Test"            val intent = Intent(Intent.ACTION_SEND)            val addressees = arrayOf(to)            intent.putExtra(Intent.EXTRA_EMAIL, addressees)            intent.putExtra(Intent.EXTRA_SUBJECT, subject)            intent.putExtra(Intent.EXTRA_TEXT, message)            intent.setType("message/rfc822")            startActivity(Intent.createChooser(intent, "Send Email using:"));        })    }}

Is it possible to modify "from" field in mailto link?

$
0
0

I'm trying to get a mailto link that would open a new outlook email window with a modified from field (i.e. to use a secondary account as it were). Is that possible?

Counting Emails in Subfolder automatically in Excel

$
0
0

I am trying to get a cell in excel to display a total count of emails in a given subfolder from a specific outlook account (which is a shared mailbox).

Two questions: How to specify which Outlook email to look in, andhow to resolve the compile error, "Next without For"

I have this so far:

Sub CountPBI()  Dim olApp As Object  Dim olNS As Object  Dim olFolder As Object  Dim olMail As Object  Dim itemCount As Long  Dim i As Long' Create an Outlook application object  Set olApp = CreateObject("Outlook.Application")' Get the Outlook namespace  Set olNS = olApp.GetNamespace("MAPI")' Specify the folder (e.g., Inbox)    Set Inbox = NS.GetDefaultFolder(olFolderInbox)    Set SubFolder = Inbox.Folders("Projects").Folders("Natural Gas").Folders("Williams/Transco").Folders("NESE").Folders("Public Comments").Folders("Individuals")' Check if it's a mail item (and potentially other criteria)      If TypeName(olMail) = "MailItem" Then' Add your counting logic here, e.g., check subject, date, etc.          itemCount = itemCount + 1      End If  Next i' Display the count in a cell (e.g., cell A1)  ThisWorkbook.Sheets("Sheet1").Range("B4").Value = itemCount' Clean up objects  Set olMail = Nothing  Set olFolder = Nothing  Set olNS = Nothing  Set olApp = NothingEnd Sub

How to Automatically Notify FastAPI Backend When an Email is Received?

$
0
0

Goal:I want to integrate my email with my FastAPI backend so that whenever a new email is received, an HTTP request is automatically sent to my backend.

Question:What is the most optimized way to implement this functionality?

Sending emails while preserving the fact of sending, but without attachments [closed]

$
0
0

I need to send a letter to the recipient's mailing address, with a huge attachment.

I want the fact of sending the letter, its title and its text to be saved in the sent section of my mailbox (the mailbox is administered by another company). The attachments that I will be sending take up quite a lot of space and I would like them not to be saved on the mail server.

I can't find a simple way to do this using mail clients (Thunderbird, Mutt). Is it possible to implement this? Maybe perl modules (Net::IMAP::Simple), python (imaplib2) or something else could help me?


Using Microsoft Access to send email through Outlook with a button click

$
0
0

I am trying to get MS Access to send a email through Outlook. In the email, I want it to pull three cells of data.

Email
Pin
FirstName

I also would like to change the "From" email address from my default address to that of a secondary address that I maintain.

For some reason, it absolutely hates my "Msg" string.

Below is my code.

    Private Sub Command7_Click()    Dim Msg As String    Dim strFrom As String    Dim strSubject As String    Msg = "Dear " & FirstName & ",<P> &" _"Below is your Personal Identification Number."<P> &" _"<P> &" _& Pin "<P> &" _"This PIN is unique to you."<P> &" _"<P> &" _"You must safeguard, and not let anyone have access to your pin."<P> &" _"<P> &" _"To initiate a wire, have your PIN available and call us at 555-555-5555."<P> &" _"<P> &" _"Questions? Please reply to this email, or call us at 555-555-5555."    Dim O As Outlook.Application    Dim M As Outlook.MailItem    Set O = New Outlook.Application    Set M = O.CreateItem(olMailItem)    strFrom = "MyDepartment@MyCompany.com"    strSubject = "ENCRYPT - Personal Identification Number (PIN)"    With M        .BodyFormat = olFormatHTML        .HTMLBody = Msg        .To = Email        .From = strFrom        .Subject = strSubject        .Display    End With    Set M = Nothing    Set O = NothingEnd Sub

If I remark ' out everything except the first line.

Msg = "Dear " & FirstName & ",<P> &" _

it will generate an email with the correct information, with the exception of changing the "From" feild in the email.

When I start adding additional lines to my "Msg? string, I get various errors, including Syntax errors, and expected: end of statement errors. I expected it to add the additional lines to my email.

I've not had much coding experience, and am very new to this. I'm just not sure how to get this working.

I can't send email from .NET application using Google SMTP client, application passwords

$
0
0

I have Google workspace, created for my mail application passwords and used the code as password in my .NET application. This worked for me in test application without Google workspace, from private mail.

However now I want to use it with custom domain and this does not work. If you recommend OAuth, then please link proper article on how to connect OAuth SMTP functionality with external application (any language, can be even bash). Currently, I get an error

535: 5.7.8 Username and Password not accepted.

Steps to reproduce:

  • domain on domain distributor
  • add it to google workspace
  • google workspace mail -> application passwords -> generate 16char password
  • in .NET:
await client.AuthenticateAsync(googleWorkspaceGmail, googleWorkspaceGmailApplicationPassword);

Edit: what should I use instead of google workspace to achieve my goal? What is the standard?

Can't connect to imap server using office365 app password and mail

$
0
0

I wrote this code for a company and they are using office365 domain. I have tried running the code first in gmail and it has worked well. Now we are trying to run it on office365 server but it's saying login error. Please note:

  1. The credentials are correct.
  2. Imap and 2FA has been enabled.
  3. We are connecting using emailid and app password.
  4. The imap server is outlook.office365.com and port is 993.

I have heard that microsoft needs ouath for high security. But in google its saying app password is also okay. Can someone please help? It's my first email automation project.

import imaplibimport loggingfrom  config import  imap_server,imap_port,my_email,my_password# Define a function to connect to the serverdef connect():    try:        imap = imaplib.IMAP4_SSL(imap_server, imap_port)        imap.login(my_email, my_password)        imap.select("Inbox")        logging.info("Successfully connected to imap.")        return imap    except imaplib.IMAP4.error:        logging.error("Login failed. Please check your email and password.",exc_info=True)    except Exception as e:        logging.error(f"Error connecting to the server {e}")        return None# Function to search the required email idsdef search_emails(imap,subject):        status, mail_ids = imap.search(None, 'UNSEEN', 'FROM', '"@domain.com"', 'SUBJECT',f'"{subject}"')        if status != 'OK':            logging.error(f"IMAP search failed for subject '{subject}'")            return []        else:            logging.info("Successfully found mails.")        return [mail_id.decode() for mail_id in mail_ids[0].split()]

Outlook add-in cannot figure out how to debug inside a Office.OnReady()

$
0
0

I've been working on an outlook add-in thats supposed to do some things with attachments when a mail is send, I've tried to use events for this but came to the conclusion that it may just be impossible in combination for what i need(If you have a solution for this that would be appreciated). I have now decided to instead use a button requiring the user to manually activate the add-in which should then modify attachments/read them and for example return to me what attachments are attached. I'm trying to just get something simple to work for something that when i press the button, the body is modified by a string hardcoded in the code. But even something as simple as that simply refuses to work. Any help or direction on what I can try/do would be appreciated.

Some context about my add-in

It's generated with yeomen generator.I'm running it in outlook classic(In any other version of outlook the entire add-in functionality doesn't work for me).Its an add-in only manifest.xml with taskpane(I have currently stripped the taskpane away from the project because i have no use for it).Its javascript

Send email using Telnet

Junit: unit test 'receive' email feature

$
0
0

There's a Java application which sends out email notifications which is triggered by user updates on UI. I am trying to write JUnit test case to verify whether email has been sent out successfully by looking for ways to receive the message.

Dumbster did not work for me because, it is meant to send email and receive mail in the test program itself.

How do I test this feature? Thanks a ton for your help.

-Vadiraj.

org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465

$
0
0

I have a Maven project, use JSF 2.2, Tomcat 7 and use Apache Commons for sending e-mail.

Here is my code

try {    // Create the email message    HtmlEmail email = new HtmlEmail();    email.setSmtpPort(465); //email.setSslSmtpPort("465");    email.setSSLOnConnect(true);    email.setHostName("smtp.gmail.com");    email.addTo("test@gmail.com", "test");    email.setFrom(getEmail(), getName());    email.setSubject(getSubject());    email.setHtmlMsg("<html>Test</html>"); // set the html message    email.setTextMsg(getText());// set the alternative message    email.send();// send the email} catch (EmailException e) {    logger.error("Exception sending email: ", e);} catch (Exception ex) {    logger.error("Exception sending email: ", ex);}

When I tried to run the code in Tomcat 7, I got the following exception:

org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465


DKIM verification fails for mail with body hash did not verify

$
0
0

Trying to do dkim verification using go lang module .https://github.com/emersion/go-msgauth/blob/master/dkim/verify.go#L212

This is the cod that gets called // VerifyWithOptions performs the same task as Verify, but allows specifying

// verification options.func VerifyWithOptions(r io.Reader, options *VerifyOptions) ([]*Verification, error) {    // Read header    bufr := bufio.NewReader(r)    h, err := readHeader(bufr)    if err != nil {        return nil, err    }

I am suspecting issue lies how we are feeding mail to VerifyWithOptions()

go func() {            defer func() {                _ = w.Close()                // this is real paranoia, I really doubt this                // can panic, but if I'm wrong, I don't want                // it to come all the way down.                r := recover()                if r != nil {                    mc.Error(LogPanicWritingMail,                        slog.Any("recovered", r),                    )                }            }()            _ = message.WriteOriginalMail(mc.Context, mc.Logger,                info, w)            _, _ = w.Write([]byte("\r\n"))        }()        verifications, err := dkim.VerifyWithOptions(            r, &dkim.VerifyOptions{                MaxVerifications: 5,                LookupTXT:        j.lookupTXT,            },        )


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>