Unable to attatch image to pug html and nodemailer
We have tested this many ways and I'm curious if we would have to add anything to the interface EmailOptions<T:any>. When the email is sent we only see the alternative from the file not rendering.
interface EmailOptions<T = any> {
/**
* The template name
*/
template?: string;
/**
* Nodemailer Message <Nodemailer.com/message/>
*
* Overrides what is given for constructor
*/
message?: Mail.Options;
/**
* The Template Variables
*/
locals?: T;
///do we need attachments?:someObj; here?
}
This is the absolute path to the image file. packages/api/image/header.jpg
This is the absolute path to the mailer file. packages/api/helper/mailer.js
This is the html.pug
img(src= 'header.jpg' alt='header' style='width:100%; height:auto;')
This is the email method
function sendSurveyEmail(application) {
email.send({
template: 'survey',
message: {
from: 'Person <person@email.org>',
to: 'Other@person.io'
},
locals: {
name: application.thisName,
patientName: application.thatName,
appUrl: process.env.APP_URL,
},
attachments: [{
filename: 'header.jpg',
path: '.public/image/header.jpg',
cid: 'header.jpg'
}]
}).catch((err) => console.log(err))
.then(() => console.log('email has been sent!'));
}
See also questions close to this topic
-
Make Query With having, count and join in Sequelize
I have two tables in MySQL, joined with a Many to Many relationship. They are as follows:
Equipments:
Field Type Id PK, Integer name Varchar description Varchar createdAt datetime Instructions:
Field Type id FK, integer name Varchar And the table that joins them as a pivot:
EquipmentInstructions:
Field Type equipmentId FK, integer instructionId FK, integer The query I'm trying to do is this, but getting all the fields, not just the name and description.
SELECT P.equipmentId, E.name, E.description FROM EquipmentInstructions P JOIN Equipments E ON P.equipmentId=E.id WHERE P.instructionId IN (1,2,3) GROUP BY P.equipmentId HAVING COUNT(*)=3;
This query returns:
equipmentId, name, description '8', 'ESPATULA', 'Espátula de cocina' '7', 'PARRILLA', 'Para asar la carne' '4', 'CUCHARÓN', 'Cuchara grande'
I am trying to pass said query to Sequelize, so far I have achieved this:
Equipment.findAndCountAll({ include: [ { model: Instruction, as: "instructions", through: { where: { instructionId: { [Op.in]: [1,2,3], }, }, }, attributes: { include: ["id"], }, }, ], group: ["id"], having: Sequelize.where(Sequelize.fn("COUNT", "*"), "=", recipeIds.length), }) .then((result) => { console.log(result); res.json(result); })
The result is correct, however, I only get the id of the equipment:
{ count: [ { id: 4, count: 3 }, { id: 7, count: 3 }, { id: 8, count: 3 } ], rows: [] }
I need to show the complete information of the equipment and additionally count how many records exist in total (by pagination issues).
-
How to ssr Svelte and pass data from express in node js
I am trying svelte and I might use it for my future website, but there is on thing that has stopped me from suing many js frameworks/compilers. It is server side rendering (one reason is I use server-less so it would be easier then prerendering). Is there a way to use express to server-side-render svelte on every request and also pass data from my node js app too so I don't have to make a bunch of other request? For example the App.svelte might be:
<script> export let data let count = 0 </script> <main> <button on:click={count++}>Increase Count BY 1</button> <h1>{data}<h1> </main>
and main.js:
import App from './App.svelte'; const app = new App({ target: document.body, props: { } }); export default app;
I want to get the data value from the server and use it in the svelte code and also sever-side-render it. Is there a way I can do this?
-
how to send long complex array with socket.io?
I have complex an array containing lots of base64 data. and I send this array to server with socket.io. If I send an array containing one or two base64 data. the function is working successfully. but if I send an array containing lots of base64 data. function does not react.
my purpose
- client will prepare templates.
- When the client clicks the save button, it sends this template to the server with socket.io.
- templates sent to the server will be saved to hdd with nodejs.
my array template
const MyArray = [ { div_id:div.id, div_innerhtml:div.innerHTML, //<img src=base64... div_backgroundimage : div.backgroundimage //base64... } ]
client-side code
const MyArray=[],SaveBtn = document.queryselector("#save_div"); const SendArray = (ARRAY)=>{ socket.emit("div_data",ARRAY); } SaveBtn.onclick = ()=>{ SendArray(MyArray); }
server-side code
socket.on("div_data",(data)=>{ console.log(data) // function does not react. let JSON_DATA = JSON.stringify(data) console.log(JSON_DATA) // function does not react. });
Is this socket.io error? What should I do or how should I research this issue?
UPDATE
network tab in devtools
for two base64 image : (function work successfully)
for four base64 image : (function does not react)
-
Toggle pynput listener at key press
I have a two-side question. I have a code as follows:
from pynput.keyboard import Key from pynput.mouse import Controller as MouseController mouse = MouseController() def make_click(x_cord, y_cord): # This is because in the program the click must have certain length of click mouse.position = (x_cord, y_cord) mouse.press(Button.left) time.sleep(0.012) mouse.release(Button.left) time.sleep(0.067) def on_press(key): try: if key.char == '1': make_click(1024,942) if key == Key.f1: # Should do the same as the '1' key press make_click(1024,942) if key == Key.enter: # Pause listener until the 'enter' key is pressed again if key == Key.enter: # Return to listener except Exception as ex: print(ex) def on_release(key): if key == Key.esc: # Stop listener return False keyboardlistener = KeyboardListener(on_press=on_press, on_release=on_release) keyboardlistener.start() keyboardlistener.join()
The main issues I'm having is that, as can be seen, pressing
1
should do the same as at the press of thef1
key. However, this only works when pressing1
and not when pressingf1
. Have seen many posts and it seems to be written correctly, however I can't manage to make it work for thef1
key.And the other question, perhaps more complicated, is that I would like to press the
Enter
key and then be able to use the keyboard without triggering theon_press
actions, meaning I could press1
and the mouse shouldn't move. Afterwards, when pressing enter again, the listener should continue -
C# Selenium driver - close all web pages after finish
[SetUp] public void Setup() { //open web page }
[Test] public void Test() { //test stuff }
C# selenium driver has two methods, you can set up for example opening browser and going to specific web page, and then testing specific elements, so you don't have to write opening part in each test method.
But then all these web pages will stay open until you close them manually. Is there an equivalent for
Setup
that runs after test has been completed, so you can close browser automatically? -
Questions at the interview?
At the job interview I was asked a question:
You are provided with standalone software which is an [(executable file).exe], which runs itself without any other files or libraries. At the same time you are documented with specifying inputs and outputs for each input. Write solutions and algorithms (pseudo code is OK) to identify ALL bugs of that software.
I tried to find documents to try to understand but still could not find it, hope everyone suggests. Thanks!
-
Routing partial view ExpressJS
I'm building a social network with NodeJS and Express. When I'm on the user profile page, I have tabs that should upload the inner view (I thought using partial views). When I click on a tab, I want to send the corresponding partial view and datas from the server to avoid refreshing all the page but I don't find a way to achieve this.
routes.js
router.get('/profile', (req, res) => { if (req.isAuthenticated()) { res.render("profile", {title: "Profil", user: req.user}); } else { res.redirect('/login'); } });
profile.pug
.column.is-7 .tabs.has-text-weight-semibold.mb-6 ul li.is-active a(class="has-icons-left" href="/profile") span.icon.is-left ion-icon(name="person") span Bio li a(class="has-icons-left" href="/profile/feed") span.icon.is-left ion-icon(name="newspaper") span Fil d'actu li a(class="has-icons-left" href="/profile/photos") span.icon.is-left ion-icon(name="camera") span Photos li a(class="has-icons-left" href="/profile/videos") span.icon.is-left ion-icon(name="film") span Vidéos li a(class="has-icons-left" href="/profile/thoughts") span.icon.is-left // ion-icon(name="chatbox-ellipses") ion-icon(name="heart") span Témoignages // uploaded partial view depending on routing here ->
How would I load partial views when routing using express ? Or should I use React or Angular ?
-
Web page won't scroll using Pug/W3.CSS
I'm building a web app to test out Node.js, Express.js, Pug, and W3.CSS. I used a template for my home page which is extremely simple, featuring two buttons and a horizontally/vertically centered h1. In other words, this home page does not need to scroll because the content is fixed. However, I'm trying to create the HTML/CSS for a page that returns multiple results from a POST request. Eventually I will be adding pagination but for now, I can't get the content to be scrollable. My POST request returns five results, but only the last 3 are displayed. For reference, here is the Pug file (remember that I'm using Pug as a template/view engine and W3.CSS classes for all of the components on the page):
doctype html title RecipeTin meta(charset='UTF-8') meta(name='viewport' content='width=device-width, initial-scale=1') link(rel='stylesheet' href='https://www.w3schools.com/w3css/4/w3.css') link(rel='stylesheet' href='https://fonts.googleapis.com/css?family=Raleway') link(rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css') script(src='/scripts.js') style. body,h1,h5 {font-family: "Raleway", sans-serif} body, html {height: 100%} .bgimg { background-image: url('/images/background.png'); min-height: 100%; background-position: center; background-size: auto; } .w3-card-4 { background-color: black; text-align: center; } p { padding: 10px; } .bgimg.w3-display-container.w3-text-white .w3-display-container .w3-display-middle each recipe in recipes .w3-card-4 h1= recipe.recipeName hr.rounded p Ingredients... hr.rounded p Method...
-
Accessing attributes of an object in body is not possible "undefined"
I have a very strange, to my point of view, problem. I am doing a post request in my Node.js application. I pass a form where one of the variables is an object place:
{"id":"0ba78ba1-c7dc-440f-b166-4b2cd6dceff0","coordinates":{"crs":{"type":"name","properties":{"name":"EPSG:4326"}},"type":"Point","coordinates":[25.28827329151016,54.69353842802546]},"place_name":"Viva Pizza & Sushi & Wok ","description":"Sushi and pizza based fast food restaurant","category":"Food","createdAt":"2021-03-17T13:25:27.619Z","updatedAt":"2021-03-17T13:25:27.619Z"}.
The problem is that i can access it as req.body.place in my function but when I try to get
req.body.place.id
id is undefined. In contrast, accessing req.body.user.id in the same way is fine. What am I doing wrong here? Accessing object attributes seems quite straightforward but it does not work in this case. Any suggestions will be helpful.
Some more code is below:
backend function:
exports.likePlace = async function (req, res) { const user = await models.User.findOne({ where: { id: req.user.id } }); const place = await models.Place.findOne({ where: { id: req.body.place.id } }); try { await user.addPlace(place, { through: { selfGranted: false } }); res.send(true); } catch (e) { console.log(e); res.send(false); } }
Making the post request:
input(type="hidden" name="place" value=places[0]) button#nope(type="submit")
-
My code for a Outlook 2016 attachment reminder doesn't display the correct dialog box
When I use this code:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean) Dim retMB As Variant Dim strBody As String Dim iIndex As Long On Error GoTo handleError iIndex = InStr(Item.Body, "attach", "attachment") If iIndex > 0 And Item.Attachments.Count = 1 Then retMB = MsgBox("Forgot attachment?" & vbCrLf & vbCrLf & "Continue?", vbQuestion + vbYesNo + vbDefaultButton2 + vbMsgBoxSetForeground) If retMB = vbNo Then Cancel = True End If handleError: If Err.Number <> 0 Then MsgBox "Sending with no attachments!" & Err.Description, vbExclamation, "ERROR!!!" End If End Sub
I want to get the "Forgot attachment?" dialog box with the message. Except I only get the "Sending with no attachments!" dialog box. Why doesn't the reminder dialog appear when the email doesn't have an attachment?
-
How do I convert this image and attach it to an email?
I'm making an app for ordering and error reports, very basic. The goal is to get input from the user, attach it to the specific form (text on top of photo from scanned form) and finally let them email me this.
Heres the main XML for filling out the form.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/recipientEt" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/background_light" android:text="anton.boman@strangnas.se" android:textAlignment="center" android:textColor="@android:color/background_light" android:textSize="1sp" tools:text="Skyddsutrustning" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@android:color/holo_orange_light" android:text="Beställning/ Felanmälan" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="36sp" tools:text="Beställning/ Felanmälan" /> <TextView android:id="@+id/subjectEt" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Ny Beställning/ Felanmälan" android:layout_marginTop="8dp" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="italic" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:text="Vänligen fyll i nedan:" android:textAlignment="center" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold|italic" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginStart="8dp" android:layout_marginTop="8dp" android:text="-Beställning eller felanmälan:" android:textAlignment="viewStart" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold|italic" /> <RadioGroup android:id="@+id/radioGroup" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"> <RadioButton android:id="@+id/radio1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Beställning" android:textSize="24sp" /> <RadioButton android:id="@+id/radio2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="Felanmälan" android:textSize="24sp" /> </RadioGroup> <TextView android:id="@+id/messageEt1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:gravity="start" android:minHeight="50dp" android:textColor="@android:color/black" android:textColorHint="@android:color/tertiary_text_dark" android:textSize="24sp" android:textStyle="bold" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="-Datum för anmälan:" android:textAlignment="viewStart" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/messageEt6" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:layout_marginStart="16dp" android:gravity="start" android:digits="0123456789./" android:background="@drawable/border" android:hint="Datum - ex. 1/1" android:minHeight="100dp" android:textColor="@android:color/black" android:textColorHint="@android:color/tertiary_text_dark" android:textSize="18sp"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="-Vilken artikel gäller ärendet?" android:textAlignment="viewStart" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold|italic" /> <Spinner android:id="@+id/spinnervilken" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:minHeight="50dp" android:layout_marginEnd="16dp" android:background="@drawable/border" android:textSize="35sp" /> <TextView android:id="@+id/vilkenarttxt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="-Beskriv ärendet (ex. lågt batteri, fungerar ej, saknas i detta rum):" android:textAlignment="viewStart" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/messageEt3" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:layout_marginStart="16dp" android:gravity="start" android:hint="Beskriv ärendet" android:inputType="textCapSentences" android:background="@drawable/border" android:minHeight="100dp" android:textColor="@android:color/black" android:textColorHint="@android:color/tertiary_text_dark" android:textSize="18sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:inputType="text" android:minHeight="100dp" android:text="-Vilken avdelning gäller ärendet:" android:textAlignment="viewStart" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/messageEt4" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:layout_marginStart="16dp" android:gravity="start" android:hint="Avdelning" android:inputType="textCapSentences" android:background="@drawable/border" android:minHeight="100dp" android:textColor="@android:color/black" android:textColorHint="@android:color/tertiary_text_dark" android:textSize="18sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="-Vilker rumsnummer gäller ärendet:" android:textAlignment="viewStart" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/messageEt41" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:layout_marginStart="16dp" android:digits="0123456789." android:gravity="start" android:hint="Rumsnummer" android:background="@drawable/border" android:inputType="number" android:minHeight="100dp" android:textColor="@android:color/black" android:textColorHint="@android:color/tertiary_text_dark" android:textSize="18sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:layout_marginEnd="16dp" android:text="-Namn på dig som beställer:" android:textAlignment="viewStart" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/messageEt5" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:layout_marginStart="16dp" android:gravity="start" android:hint="Namn på dig som beställer:" android:inputType="textCapWords" android:background="@drawable/border" android:minHeight="100dp" android:textColor="@android:color/black" android:textColorHint="@android:color/tertiary_text_dark" android:textSize="18sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:text="-Namn på enhet:" android:textAlignment="viewStart" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/messageEt8" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:layout_marginStart="16dp" android:gravity="start" android:hint="Namn på enhet" android:background="@drawable/border" android:inputType="textCapWords" android:minHeight="100dp" android:textColor="@android:color/black" android:textColorHint="@android:color/tertiary_text_dark" android:textSize="18sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:text="-Telefonnummer:" android:textAlignment="viewStart" android:textColor="@android:color/black" android:textSize="24sp" android:textStyle="bold|italic" /> <EditText android:id="@+id/messageEt7" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:digits="0123456789.-" android:gravity="start" android:hint="Telefonnummer" android:background="@drawable/border" android:inputType="number" android:minHeight="100dp" android:textColor="@android:color/black" android:textColorHint="@android:color/tertiary_text_dark" android:textSize="18sp" /> <Button android:id="@+id/VidareBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dp" android:layout_gravity="center" android:background="@android:color/holo_orange_light" android:text="Skapa Beställningsblankett" android:textColor="@android:color/black" android:textSize="18sp" /> <Button android:id="@+id/sendEmailBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dp" android:layout_gravity="center" android:background="@android:color/holo_orange_light" android:text="RÖR EJ" android:textColor="@android:color/black" android:textSize="18sp" /> </LinearLayout> </ScrollView> </RelativeLayout>
Along with the Main activity.
class MainActivity : AppCompatActivity() , AdapterView.OnItemSelectedListener { lateinit var changeActivityButton: Button lateinit var messageEditText: EditText lateinit var messageEditText2: EditText lateinit var messageEditText3: EditText private var spinner: Spinner ? = null private var arrayAdapter: ArrayAdapter<String>? = null private var result:TextView ? = null private var itemlist = arrayOf("Rörelselarm", "Dörrlarm", "Larmknapp", "Cobstelefon", "Rumsenhet", "Talpuck", "Övrigt") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) messageEditText = findViewById(R.id.messageEt6) messageEditText2 = findViewById(R.id.messageEt3) //messageEditText3 = findViewById(R.id.messageEt1) changeActivityButton = findViewById(R.id.VidareBtn) changeActivityButton.setOnClickListener { val intent = Intent(this@MainActivity, BildmedText::class.java) val message4l = messageEt4.text.toString().trim() val message5l = messageEt5.text.toString().trim() val message6l = messageEt41.text.toString().trim() val message7l = messageEt7.text.toString().trim() val message8l = messageEt8.text.toString().trim() val messages = arrayOf(message8l,message4l,"Rum:", message6l) val messages2 = arrayOf("Anmält av:", message5l,"Telefonnummer", message7l) val messagelang = messages.joinToString(separator = " ") val messagelang2 = messages2.joinToString(separator = " ") val message = messageEditText.text.toString() val message2 = messageEditText2.text.toString() //val message3 = messageEditText3.text.toString() intent.putExtra("message_key", message) intent.putExtra("message_key2", message2) intent.putExtra("message_key3", messagelang) intent.putExtra("message_key4", messagelang2) startActivity(intent) val button = findViewById<Button>(R.id.VidareBtn) button.setOnClickListener { val intent = Intent(this, BildmedText::class.java) startActivity(intent) } } spinner = findViewById(R.id.spinnervilken) result = findViewById(R.id.vilkenarttxt) arrayAdapter = ArrayAdapter(applicationContext, android.R.layout.simple_spinner_item, itemlist) spinner?.adapter = arrayAdapter spinner?.onItemSelectedListener = this radioGroup.setOnCheckedChangeListener { group, checkedId -> if (checkedId == R.id.radio1) { messageEt1.text = radio1.text } if (checkedId == R.id.radio2) { messageEt1.text = radio2.text } }
Next step: Load the text onto the form image and take a screenshot of the form and later on attach it to an email.
The XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/BildmedText" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" tools:context=".BildmedText"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/image" /> <ImageView android:id="@+id/imageView2" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <TextView android:id="@+id/textdatum" android:layout_width="60dp" android:layout_height="wrap_content" android:layout_marginTop="100dp" android:layout_marginStart="120dp" android:padding="4dp" android:textColor="@android:color/black" android:textSize="12sp" android:textStyle="italic" /> <TextView android:id="@+id/textnamnuppgifter" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:width = "0dp" android:layout_marginStart="215dp" android:layout_marginTop="115dp" android:padding="4dp" android:textColor="@android:color/black" android:textSize="8sp" android:textStyle="italic" /> <TextView android:id="@+id/textnamnuppgifter2" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:width = "0dp" android:layout_marginStart="215dp" android:layout_marginTop="135dp" android:padding="4dp" android:textColor="@android:color/black" android:textSize="8sp" android:textStyle="italic" /> <TextView android:id="@+id/beskriv" android:layout_width="300dp" android:layout_height="wrap_content" android:layout_marginTop="170dp" android:layout_marginStart="30dp" android:padding="4dp" android:textColor="@android:color/black" android:textSize="10sp" android:textStyle="italic"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" android:text="Take screenshot" /> </RelativeLayout>
Second activity
import android.graphics.Bitmap import android.graphics.Color import android.view.View import android.widget.Button import android.widget.ImageView import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity @Suppress("DEPRECATION") class BildmedText : AppCompatActivity() { private lateinit var main: View private lateinit var imageView: ImageView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_bildmed_text) title = "Felanmälan Trygghetslarmet" val message = intent.getStringExtra("message_key") val message2 = intent.getStringExtra("message_key2") val message3 = intent.getStringExtra("message_key3") val message4 = intent.getStringExtra("message_key4") val messageTextView: TextView = findViewById(R.id.textdatum) val messageTextView2: TextView = findViewById(R.id.beskriv) val messageTextView3: TextView = findViewById(R.id.textnamnuppgifter) val messageTextView4: TextView = findViewById(R.id.textnamnuppgifter2) messageTextView.text = message messageTextView2.text = message2 messageTextView3.text = message3 messageTextView4.text = message4 main = findViewById(R.id.BildmedText) imageView = findViewById(R.id.imageView2) val btn: Button = findViewById(R.id.button) btn.setOnClickListener { val b: Bitmap = Screenshot.takeScreenshotOfRootView(imageView) imageView.setImageBitmap(b) main.setBackgroundColor(Color.parseColor("#999999")) } } companion object Screenshot { private fun takeScreenshot(view: View): Bitmap { view.isDrawingCacheEnabled = true view.buildDrawingCache(true) val b = Bitmap.createBitmap(view.drawingCache) view.isDrawingCacheEnabled = false return b } fun takeScreenshotOfRootView(v: View): Bitmap { return takeScreenshot(v.rootView) } } }
What's the best approach to proceed and attach the image to an email?
Or should I use a completely different approach altogether?
Cheers
-
Facing issues in downloading a particular attachment from gmail through Python
I have the below piece of code which works fine for downloading CSV files. But I'm trying to download a file without any extension name where this is failing. The
part.get_filename()
is not fetching anything and hence the code is failing with errorNameError: name 'fileName' is not defined
. The search is working correctly and identifying the particular email.import gspread from oauth2client.service_account import ServiceAccountCredentials import pandas as pd import os import imaplib import email #from email.header import decode_header #import webbrowser import os import datetime import time import glob import shutil today = datetime.date.today() yday = today - datetime.timedelta(days=5) # account credentials username = "xyz@gmail.com" with open(r'C:\Users\xyz\Downloads\Google sheet key\gmail_app_pwd.txt','r') as pwd: password=pwd.read() # create an IMAP4 class with SSL mailBox = imaplib.IMAP4_SSL("imap.gmail.com") # authenticate mailBox.login(username, password) svdir = r'C:\Users\xyz\Downloads\Work' boxList = mailBox.list() # print(boxList) mailBox.select() searchQuery = '(SUBJECT "Mailer as on ' + str(yday) +'")' result, data = mailBox.uid('search', None, searchQuery) ids = data[0] # list of uids id_list = ids.split() i = len(id_list) #x=0 for x in range(i): latest_email_uid = id_list[x] # fetch the email body (RFC822) for the given ID result, email_data = mailBox.uid('fetch', latest_email_uid, '(RFC822)') raw_email = email_data[0][1] # converts byte literal to string removing b'' raw_email_string = raw_email.decode('utf-8') email_message = email.message_from_string(raw_email_string) # downloading attachments for part in email_message.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: continue fileName = part.get_filename() if bool(fileName): filePath = os.path.join(svdir, fileName) if not os.path.isfile(filePath) : fp = open(filePath, 'wb') fp.write(part.get_payload(decode=True)) fp.close() subject = str(email_message).split("Subject: ", 1)[1].split("\nTo:", 1)[0] print('Downloaded "{file}" from email titled "{subject}" with UID {uid}.'.format(file=fileName, subject=subject, uid=latest_email_uid.decode('utf-8'))) mailBox.close() mailBox.logout()
-
how to convert Object Promise to string javascript
I try to send data from the backend to mail the problem that when I receive the mail the data showed like
[object Promise]
not like a string I try to convert it but I'm stack to do itwhen I
console.log(nameAr)
orconsole.log(PassWord)
I get the data with no errors but in the mail it's lookobject Promise
can you help me please
here the Nodejs code :
router.post("/sendmail", (req, res) => { console.log("request came"); let user = req.body; sendMail(user, info => { console.log(`the mail has beed send and the id is ${info.messageId}`); res.send(info); }); }); async function sendMail(user, callback) { let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 587, secure: false, auth: { user:"my-email@gmail.com", pass: "mypassword" } }); nameAr = getusername(user.DECAFFE); PassWord=changepassword(user.DECAFFE) let mailOptions = { from: 'my-email@gmail.com', to: "email@gmail.com", subject: "subject", html: `<h1>HI here you password${nameAr.toString()}</h1><br><h4>${PassWord}</h4>` }; let info = await transporter.sendMail(mailOptions); callback(info); } async function getusername(DECAFFE) { const name = await DRAFBIE.findOne({ DECAFFE: DECAFFE }) console.log("the name is "+name.AR_DELAFFE) return name.AR_DELAFFE; } async function changepassword(DECAFFE) { const saltRound = 10; const password = generator.generate({ length: 8, numbers: true }) console.log(password) const drafbie = await DRAFBIE.findOneAndUpdate({ DECAFFE: DECAFFE}, { $set: { MOT_PASS: await bcrypt.hash(password, saltRound), } }, { new:true } ); await drafbie.save(); console.log("the password is "+password) return password }
-
Nodemailer error: The "path" argument must be of type string. Received undefined
I know this error has been often reported on SO, but I can't solve this issue, which is related to Nodemailer.
When trying to send an email, the server crashes with this error:
err checkout TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined at new NodeError (node:internal/errors:329:5) at validateString (node:internal/validators:129:11) at Object.join (node:path:1081:7) at TemplateGenerator.render (/Users/myname/Desktop/Code/myapp/server/node_modules/nodemailer-express-handlebars/lib/generator.js:19:29) at /Users/myname/Desktop/Code/myapp/server/node_modules/nodemailer-express-handlebars/lib/index.js:9:19
The code is:
require("dotenv").config(); import nodemailer from "nodemailer"; import hbs from "nodemailer-express-handlebars"; const transporter = nodemailer.createTransport({ service: "gmail", auth: { user: process.env.NODEMAILER_EMAIL, pass: process.env.NODEMAILER_PASSWORD, }, tls: { rejectUnauthorized: false, }, }); transporter.use( "compile", hbs({ viewEngine: "express-handlebars", viewPaths: "../mails/", extName: ".hbs", }) ); export class MailControler { static confirmSignup( { email, username }, price: string ) { return transporter.sendMail({ from: appMail, to: email, subject: "Hello", template: "confirmSignup", context: { username }, }); } }
The route is working, the transporter is defined (I can log it in the terminal with the correct informations), the express-handlebars context is defined (I can also log the variable
username
), I can also log the process.env parts.The structure is:
- controler
- mail.ts
- mails
- confirmSignup.hbs
So there is no directory error here.
What is wrong with this code? Where is this undefined path argument?
- controler
-
Content-Transfer-Encoding : quoted-printable is converting "="(equal sign) to "=3D" causing the mail sent to user (using nodemailer) to bug out
async function sendMail(to, name) { var message await userSchema.findOne({ email: to }, (err, data) => { // This is the line message = '<a href="www.google.com"' + '>Verify</a>' }) let transporter = nodemailer.createTransport({ host: "smtp.gmail.com", port: 587, secure: false, auth: { user: <mymail>, pass: <mypass>, }, }); let info = await transporter.sendMail({ from: '"<Name>" <mymail>', to: to, subject: <subject>, text: <text>, html: message, }); }
This is what the user receives when I click the "Show Original" option in Gmail.
The Error is that on the user-side/ client-side the mail received by the user doesn't contain the link corresponding to the anchor tag, it's just a plain text instead of it being a link due to the encoding.
The quoted-printable Content-Transfer-Encoding converts the = to =3D, causing the anchor tag to be sent like this to the user in the email ------>
<a href=3D"<link>">Verify</a>
instead of being<a href="<link>">Verify</a>
and this renders the tag invalid, causing it to display as plain text, I tried to add the protocol in the href value and see if it works but to no avail, Also tried manually setting the encoding (in nodemailer configuration) to 'base64' but doesn't help.Any suggestions are welcome.
If there's no other way, I'll also mention my requirement so that y'all can help with that. Basically, my user signs up and has to verify, receives OTP via email, has to enter it, Now, The mail with the OTP has to have a LINK to a page where the user WILL enter the OTP and this updates in the DB that the user has verified, unless verified user can't access the app.